简体   繁体   English

在PHP中定义变量有麻烦吗?

[英]Trouble defining a variable in PHP?

Alright, so a content page uses this: 好了,因此内容页面使用以下代码:

$tab = "Friends";
$title = "User Profile"; 
include '(the header file, with nav)';

And the header page has the code: 标题页包含以下代码:

if ($tab == "Friends") { 
echo '<li id="current">'; 
} else { 
echo '<li>'; 
}

The problem is, that the if $tab == Friends condition is never activated, and no other variables are carried from the the content page, to the header page. 问题是, if $tab == Friends条件永远不会被激活,并且没有其他变量从内容页面传送到标题页面。

Does anyone know what I'm doing wrong? 有人知道我在做什么错吗?

Update: Alright, the problem seemed to disappear when I used ../scripts/filename.php , and only occurred when I used a full URL? 更新:好的,当我使用../scripts/filename.php时,问题似乎消失了,仅当我使用完整的URL时才出现?

Any ideas why? 有什么想法吗?

When you include a full URL, you're not including the PHP script -- you're including the HTML it generates. include完整的URL时,就不包含PHP脚本,而是要包含它生成的HTML。 It's just like you went to http://wherever.your.url.goes , but it's done by the server instead of the browser. 就像您访问了http://wherever.your.url.goes ,但这是由服务器而不是浏览器完成的。 The script runs in a whole separate process, caused by a separate request from the server to itself, and none of the $variable s are shared between the two. 该脚本在整个单独的过程中运行,这是由服务器对自身的单独请求引起的,并且$variable都不在两者之间共享。

Short version: When you include http://wherever.your.url.goes , $tab will always be blank. 简短版本:如果包含http://wherever.your.url.goes ,则$tab始终为空白。 If you include the actual file name, the variable will be shared. 如果包含实际文件名,则将共享该变量。

Your code as posted should work. 您发布的代码应该可以正常工作。 How are you actually including that file? 您实际上如何包含该文件? Does that happen inside a function? 这会在函数内部发生吗? Then you need to use the global statement for it to work. 然后,您需要使用global语句才能使其正常工作。 Example: 例:

File 1: 文件1:

function my_include($file) {
    global $tab; // <-- add this
    include '/some/path/' . $file;
}

$tab = 'Friends';
my_inlcude('file_2.php');

File 2: 档案2:

if ($tab == 'Friends') { ... }
  1. Now you see why it's awful practice to post some stubs and skeches instead of the real code 现在您了解为什么张贴一些存根和草图而不是真实的代码是可怕的做法

  2. Try to think, Your question is not a rocket science. 尝试思考,您的问题不是火箭科学。 Include is like copy-pasting code in place of include operator. 包含就像复制粘贴代码一样代替包含运算符。 Go load your inclided URL in browser, copy resulting code and paste it into your first file and see. 在浏览器中加载您的隐含URL,复制生成的代码并将其粘贴到第一个文件中即可查看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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