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?

  • Well, in general, you yourself said to yourself ... declare the header variable, add the tag content there, and output it wherever you need - AlexandrX
  • well, I can add that you need to declare it in a separate file (say, header.php ), and enable it wherever you need to output a variable ( require 'header.php'; echo $header; ) - AlexandrX
  • and how “right” - it depends on what site you are developing ... everyone has “what’s his own” how is right :) - AlexandrX

3 answers 3

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> 
test2.php
 <? 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; }