I develop a website and run into a problem when you need to connect one <head> on different pages, but stupidly copying and pasting is not an option. For example, you will need to change something or add. So, in order not to have to do this every time, is it possible to somehow put the contents of the <head> into a variable and output it on the main page with the help of a <?php echo $header; ?> <?php echo $header; ?> ? And how to do it right?
|
3 answers
As an example:
test.php
<?php class Head { protected static $head = 'TestHead'; public static function getHead() { return self::$head; } } ?> <!DOCTYPE html> <html> <head> <title><? echo Head::getHead() ?></title> <meta charset="utf-8"> </head> <body> </body> </html> <? include_once "test.php" ?> <!DOCTYPE html> <html> <head> <title><? echo Head::getHead() ?></title> <meta charset="utf-8"> </head> <body> </body> </html> |
It is possible, for example, to write a header into a variable using the HEREDOC syntax.
$header = <<< HEADER <!DOCTYPE html> <html> <head> <title>Заголовок</title> <meta charset="utf-8"> </head> HEADER; Declare it in some file and connect it. Or just put in a separate file and connect it.
|
J. Doe, your example will show him the same header. If you implement on OOP (although why oop?), Then instead of public static function getHead () you need something, like a constructor, passing parameters to it for each page. Like that:
public function __construct($head) { $this->head = $head; } |
header.php), and enable it wherever you need to output a variable (require 'header.php'; echo $header;) - AlexandrX