Can you use a variable above when it is declared below?

4

I have some includes in a PHP page, including other pages for use in friendly URL, etc. I thought about using Global variables and even constants, but it is not working.

Does anyone know if there is a way without using Cookies, Sessions, or Cache to use a variable that is only declared below?

Example:

echo $variavelA;
$variavelA = 1;

In this logic, however obviously this way does not work.

CLEAREST EXAMPLE:

<!DOCTYPE html>
<html lang="pt-br">
<head>
<title><?php echo $pagina; ?></title>
</head>
<body>
<?php include('home.php'); ?>
</body>
</html>

A very common example! Let's assume that in the home.php file we have:

$pagina = "Home";

The variable is declared below where I want to call it.

    
asked by anonymous 09.03.2014 / 20:06

7 answers

1

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.

    
09.03.2014 / 21:28
2

Capturing the passed value via get is possible.

 <!DOCTYPE html>
    <html lang="pt-br">
        <head>
            <title> <?php 

                      $pagina= isset($_GET['pagina']) ? $_GET['pagina'] : "Inicial";
                      echo $pagina; 

                    ?> 
             </title>
           </head>
           <body>

<ul id="menu">
    <li><a href="?pagina=home">Home</a></li>
    <li><a href="?pagina=tutoriais">Posts</a></li>
    <li><a href="?pagina=contato">Contato</a></li>                      
</ul>
<?php

    $pg = !isset ($_GET['pagina']) ? $pg == "home" : $_GET['pagina'];

        if( is_file( "$pg.php" ) )
            include "$pg.php";
        else{
            include 'home.php';
        }           

?>
</body>  
</html>
<ul id="menu">
    <li><a href="?pagina=home">Home</a></li>
    <li><a href="?pagina=tutoriais">Posts</a></li>
    <li><a href="?pagina=contato">Contato</a></li>                      
</ul>
<?php

    $pg = !isset ($_GET['pagina']) ? $pg == "home" : $_GET['pagina'];

        if( is_file( "$pg.php" ) )
            include "$pg.php";
        else{
            include 'home.php';
        }           

?>
</body>  
</html>
    
10.03.2014 / 12:51
1

This is unlikely to get you by the fact that other than javascript PHP runs only when the page loads, what I recommend you do is an AJAX call to change the name

    
09.03.2014 / 20:53
1
<?php
   include('home.php'); 
   $pagina = "Home";
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<title><?php echo $pagina; ?></title>
</head>
<body>
</body>
</html>

In a video of a course like that, at least that code worked.

    
09.03.2014 / 21:02
0

Unfortunately it is not possible to include a .php file after the code that depends on it as already pointed out in the answers; in my opinion, it is even simpler to include the files of which the code is dependent on the top, as this facilitates control under the dependencies of the file.

So, according to your example, the code below would fit the situation well without further details:

<?php include('home.php')
 /*Se a variável $página do arquivo home.php já contiver o valor 'Home',
  nem é preciso colocá-la aqui.*/
?>

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <title> <?php echo($pagina); ?> </title>
    </head>
    <body>
    </body>
</html>
    
09.03.2014 / 22:31
0

I do not know about SEO but <title> can be placed outside%% of the browser that reads it right away. Thinking about the <head> empty side adding via javascript, is able to have the same effect (for SEO, or even better in the case of <title> out of place filled, than empty).

    
10.03.2014 / 00:51
0

This is impossible, because declaring:

echo $isso;

You are passing a parameter that does not exist, but if you declare:

echo $isso = "Aquilo";

Then the situation changes, because you pass a parameter to the $ variable, making it readable and evaluable to output.

But declare $isso without a value assigned to variable $ this will not return anything other than an error saying that the variable has not been defined.

    
10.03.2014 / 01:18