You can not call a variable before its declaration. This is applicable to any programming language (as it is understood by the author itself; some information about declaring variables in PHP in the documentation here ). What is done is the declaration of a variable (constant, function ...), then its use.
Knowing this, there are several ways to solve the problem.
Handling tag <title></title>
with javascript (!)
Perhaps the first thing that comes to mind is to use javascript for the manipulation of the <title></title>
tag. However , what should be noted in this case is that JavaScript is a client-side
language, in other words, it is interpreted next to the "client". Therefore, the system will suffer several damages if it is requested in other environments, in search engines (Google, Bing ...) is an example of this. Therefore, it becomes impracticable.
<!-- template.php -->
<!doctype html>
<html lang="pt-br">
<head>
<title></title>
</head>
<body>
<?php include('home.php'); ?>
</body>
</html>
<!-- home.php -->
<script>document.title = 'Home';</script>
PHP template systems
Another would be the use of templates. Several are available in the market. I could cite the blade
of Laravel (example of version 5.6), which can also be applied to other projects. Examples: jenssegers / blade spatie / laravel-blade , and several others.
Using your own template engine
For a simple and quick manipulation, I recommend using friendly urls with .htaccess
, and thus doing the url handling, and finally the inclusion of the template that includes the php
file.
Explanation:
# exemplo de estrutura simples de arquivos
├- .htaccess
├- templates/
└- template.php
├- views/
└- home/
└- home.php
├- controllers/
└- HomeController.php
└- App
└- Core.php
The .htaccess:
This file will be responsible for the manipulation of the url. In it you will treat the url and finally will have the name of the class and the method that should call. I've separated here a good question (here in stackoverflow) about it.
The App \ Core.php class:
This class will receive the information contained in the url and finally it should arrive at the file controllers/HomeController.php
(or other, depending on the url), and finally, it will be responsible for setting the variables, both templates/template.php
, and views/home/home.php
(or other files, again, according to the url).
There could be a method similar to:
public function index() {
$title = 'Bem vindo!';
return $this->view(array('view'=>'views/home/home.php', 'title'=>$title));
}
Finally, the view
method will search for the templates/template.php
file and within it there will be an include for views/home/home.php
(as called by HomeController::index
). The template file could look like:
...
<title><?php echo "{$data['title']} - Meu site"; ?>
</head>
<body>
<?php require_once($data['view']) ;?>
...
Of course! Making the right adaptations.