Home  >  Q&A  >  body text

PHP variable rewriting

In header.php, there is a variable $title defined in the same location (depending on the URL of the page). In one of the inner pages, I want to override $title since it is taken from the database there. For example: in header.php there is

if (...) {$title = "Section 1";}

Then echo $title

In inner.php-

include(header.php); ... SELECT .....

$title = "Page 1";

Of course this won't work. Tried using globals with no success. How to override $title variable in inner.php (header.php)? Thanks for the advice, I don't know much about PHP.

Tried using globals or even functions, but not sure

P粉933003350P粉933003350306 days ago445

reply all(1)I'll reply

  • P粉204079743

    P粉2040797432024-01-11 00:18:23

    Computers will do what you tell them in the order you tell them. If you say this:

    1. Set the title to "Section 1".
    2. Read the title.
    3. Set the title to "Page 1".

    The computer will perform each step in sequence. In step 2 it will read "Part 1" and in step 3 there is no way to make it "unsay" and say something different.

    This is basically what your current code is doing, with a few extra steps in between:

    1. Contains "header.php"
    2. (in header.php) Set the header to "Section 1" based on the URL
    3. (in header.php) Display header
    4. Do something with the database
    5. Set title to "Page 1"
    6. Show the rest of the page

    Step 5 cannot affect step 3; this has already happened.

    The usual way to avoid this is to divide the program into two stages: the first stage Prepare the data , get the data from the database and make decisions about the page title and so on; the second stage Display data and make decisions based only on acquired data.

    So, in your case, you can split the data part of "header.php" into separate "startup.php" with the following steps:

    1. Contains "startup.php"
    2. (In startup.php) Set the title to "Section 1" based on the URL
    3. Do something with the database
    4. Set title to "Page 1"
    5. Contains "header.php"
    6. (in header.php) Display header
    7. Show the rest of the page

    Titles in headers are now displayed after all logic has been run, and can be displayed as "Page 1" instead of "Section 1".

    reply
    0
  • Cancelreply