php variable changes
FIXED!
I have 2 php pages that both define the variable "title" as something different. However, echoing the variable on both pages resul开发者_JAVA百科ts in the first page's variable's value being displayed on both pages. Any idea why and how I could get the variable to change for each page?
first php page:
<?php
$title = "Posts";
echo $title;
?>
This displays "Posts".
second php page:
<?php
$title = "New Posts";
echo $title;
?>
This also for some reason displays "Posts". Shouldn't this page display "New Posts"?
If you are including the second page on the first page before you define $title
on the first page, then the included value will be overwritten.
Are all of your variables defined in the global namespace? If so, this problem will be inevitable when you're including PHP files within other PHP files.
You could resolve the problem by properly encapsulating your variables within a class or namespace; for example:
In file one:
<?php
namespace included;
$title = "original title!";
?>
And in file two:
<?php
namespace including;
require_once "file_one.php";
$title = "new title!";
echo \included\$title;
echo \including\$title;
echo $title;
?>
Which will display:
original title!
new title!
new title!
精彩评论