简体   繁体   中英

Rewrite the variable (PHP)

In header.php there is a variable $title which is defined in the same place (depending on the URL of the pages). 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";} 

and then echo $title

And in inner.php -

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

$title = "Page 1";

And this, of course, does not work. Tried to use global but without success. How to rewrite the $title variable from inner.php (from header.php)? Thanks for the advice, I don't know much about PHP.

Tried to use global and even function but not shure about it

Computers are very literal about doing what you tell them, in the order that you tell them. If you say this:

  1. Set the title to 'Section 1'.
  2. Read out the title.
  3. Set the title to 'Page 1'.

A computer will do each step in turn. At step 2, it will read out 'Section 1', and there's no way for step 3 to make it "unsay" that and say something different.

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

  1. Include 'header.php'
  2. (in header.php) Set the title based on URL, to 'Section 1'
  3. (in header.php) Display the title
  4. Do some stuff with the database
  5. Set title to 'Page 1'
  6. Display the rest of the page

There's no way for step 5 to affect step 3; it's already happened.

The usual way to avoid this is to structure your program into two stages: the first stage prepares the data , fetching from databases, making decisions about things like page titles; the second stage displays the data , making decisions only based on data that's already been fetched.

So in your case, you might split the data parts of 'header.php' into a separate 'startup.php', and the steps would look like this:

  1. Include 'startup.php'
  2. (in startup.php) Set the title based on URL, to 'Section 1'
  3. Do some stuff with the database
  4. Set title to 'Page 1'
  5. Include 'header.php'
  6. (in header.php) Display the title
  7. Display the rest of the page

Now the title in the header gets displayed after all the logic has run, and can show as 'Page 1' rather than 'Section 1'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM