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

Asked

Viewed 1,132 times

4

I have some includes on a PHP page, with inclusion of other pages for user friendly URL, etc. I thought of using Global variables and even constant, but it’s not working.

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

Example:

echo $variavelA;
$variavelA = 1;

In this logic, but 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.

  • What are you trying to do necessarily? Could you go a little deeper? Abs

  • Your question is unclear because it is so general. Have some concrete example that you want to make work?

  • Check out the issues I made above in the question...

  • 1

    Rewrite the code and use output_flush solves? I don’t program in PHP, I just imagine this.

  • I’ve tried before and it doesn’t work for what I tested...

8 answers

2

Capturing the value passed 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>

1

this is kind of unlikely that you get by the fact that unlike javascript PHP runs only when the page loads, what I recommend you do is an AJAX call to change the name

  • I imagined this too, I even found that using global variables could effect such an action. But thank you!

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 this way, at least in that code it worked.

  • I appreciate your interest, that way I could not because the home page in the case, has html tags, since my site is factored and index just makes the includes of the sequences. But I appreciate your interest in trying to solve my problem!

1


It is not possible to call a variable before it is declared. This is applicable to any programming language (as understood by the author himself; some information about variable declaration 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.

Tag manipulation <title></title> javascript (!)

Perhaps the first that comes to mind is to use javascript for tag manipulation <title></title>. However, what should be noted in this case is that Javascript is a language client-side, in other words, it is interpreted alongside the "client". Thus, the system will suffer several damages if requested in other environments, in search engines (Google, Bing...) is an example of this. Soon, it becomes unviable.

<!-- 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>

Templates systems in PHP

Another would be the use of templates. Several are available in the market. I could quote the blade of Laravel (example of version 5.6), which can also be applied to other projects. Examples: jenssegers/Lade, spatie/Laravel-Blade, and several others.

Use of your own template engine

For simple and fast handling, I recommend using friendly urls with .htaccess, and thus doing the url processing and, finally, the inclusion of the template that includes the file php.

Explanation:

# exemplo de estrutura simples de arquivos
├- .htaccess
├- templates/
   └- template.php
├- views/
   └- home/
      └- home.php
├- controllers/
    └- HomeController.php
└- App
   └- Core.php

O . htaccess: This file will be responsible for handling the url. In it you will handle the url and finally have the name of the class and method you should call. I have separated here a good question (here at stackoverflow) regarding.

The App Core.php class: This class will receive the information contained in the url and finally should reach the file controllers/HomeController.php (or other, according to the url), and finally, this, will be responsible for setting the variables, both for templates/template.php, how much to views/home/home.php (or other files, again, depending on 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 method of view search the file templates/template.php and within this there will be a 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 appropriate adaptations.

  • Look, it was the most practical answer that solved my problem, I hadn’t thought about putting a script on the page. Solved in a simple and practical way, since I did not need to adapt the site for this. Thank you.

  • This solves, however, the biggest problem you will have is in relation to SEO.

  • Sure, this is an effective solution and solves the problem, but there are much better and organized ways to solve this kind of thing.

  • You have some examples?

0

I created a mobile first inclusive project for resolutions 240x340.(very old cell phone). On larger screens opens the tools on the side, app type.

Imagine an index just of include. example of my index

 <?php
     require_once('header.php'); 
     require_once('navmenu.php');
     require_once('logo-perfil.php'); // define tamanhos e medidas aceitáveis
     require_once('conecta_bd.php');// deixa o banco de dado conectado para o próximo include.
 require_once('status.php');// div para ferramentas e o bloco de resultado
 require_once('footer.php');
?>

  status.php tem três divs principais. 

One result, two other tools to call a result.

See that the result div is in the middle of html. So it generates a bug such as showing a page variable in the head.

 Solução: Criar ferramentas em forma de formulários

<form action="index.php"> <input name="page" value="paginainclude" />

This way resolves more generates in the head another error. mainly when accessing the page without logging in, because the post has not been sent yet. I put in the head the following solution

<!DOCTYPE html>
        <html lang="pt-br">

        <head>
          ...
          <?php 
    if(!isset($_POST['page'])){$page_section = "Home";}else{$page_section = $_POST['page'];}
    echo '<title>Santidade - ' . $page_section. '</title>';
    ?> ...

        </head>

        <body>

          ...
          <div id="ferramenta">barra de ferramenta. Ação, chamar arquivo cadastro-> e por na div de resultado " echo'
            <form action="index.php" method="post"><input type="submit" name="page" value="Cadastro"> </form>';. pode ser posto no link em nav Também etc... status.php -> na div id="resultado" eu chamo: require-once('cadastro.php');// registrar novo login... ... serviços do include cadastro

" Worked With the if used in head killed the home bug and first access. When one logs off or enters the first time there is no bug, because the $page_section variable returns 'home'.

The login as you know is in the Cook or $Section of the index itself that will serve for each include. Or not, if it cancels the sections

This way when generating the post it automatically embeds another include when being clicked.

In this include inside the div=results It is possible to make a page with new tools by calling new includes for example.

This way you can create separate, independent projects with the same mask as the "APP".

Just focus on the result container whose include is called in the head by controlling the entire page.

The login section is in each include header that works separately, taking advantage of the cookie and accessing sublevels and login access levels.

   principal. 

I avoid much writing It helps to avoid thinking about the entire project at all times. Makes it easy to place independent pages, with requested mysqli, or include data. know the page with errors or container that someone created. Giving errors just select another tool. And the client does not leave the index page.

0

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

Therefore, as your example, the code below would already suit the situation well without more 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>
  • In this case it would not be possible because I have the website factored by parts. has only logical parameters, such as server connection, sets and some calls from others includes to mount the site. So including the above home I would be changing the sequence of my tags. But the answer below helped a lot, thank you for your interest in trying to solve my problem!

0

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

  • I don’t know about SEO either, but I’ve used <title> outside of <head> other times, but this is an academic project, so such a placement would be incorrect. Thanks.

  • @Tiagoboeing Oh yes! Beauty then.

0

This is impossible, because declaring:

echo $isso;

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

echo $isso = "Aquilo";

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.