[英]PHP comparison operators and statements of the form if (!foo())
Here is my little script, and from writing it I've learned that I've no idea how PHP handles variables... 这是我的小脚本,通过编写它,我了解到我不知道PHP如何处理变量...
<?php
$var = 1;
echo "Variable is set to $var <br />";
if (!foo()) echo "Goodbye";
function foo()
{
echo "Function should echo value again: ";
if ($var == 1)
{
echo "\$var = 1 <br />";
return true;
}
if ($var == 2)
{
echo "\$var = 0 <br />";
return false;
}
}
?>
So, here is how I thought this script would be interpreted: 因此,这就是我认为该脚本的解释方式:
The statement if (!foo)
would run foo()
. if (!foo)
语句将运行foo()
。 If the function returned false
, it would also echo "Goodbye" at the end. 如果该函数返回false
,则它还将在末尾回显“ Goodbye”。
The function foo()
would check whether $var == 1
or 2
(without being strict about datatype). 函数foo()
将检查$var == 1
还是2
(对数据类型不严格)。 If 1 it would echo "Function should echo value again: 1", and if 2, it would echo the same but with the number 2. 如果为1,则将回显“函数应再次回显值:1”;如果为2,则将回显相同的函数,但编号为2。
For some reason both if statements inside foo()
are being passed over (I know this because if I change the first if statement to if ($var != 1)
, it passes as true, even if I declared $var = 1
. 由于某种原因, foo()
中的两个 if语句都将被传递(我知道这是因为,如果我将第一个if语句更改为if ($var != 1)
, 即使我声明 $var = 1
,它也将传递为true。
What's happening here? 这里发生了什么事? I thought I had all this down, now I feel like I just went backwards :/ 我以为我把这一切都弄糟了,现在我觉得我倒退了:/
The function doesn't know what $var
is. 该函数不知道$var
是什么。 You'd have to pass it in, or make it global: 您必须将其传递或使其全局化:
function foo() {
global $var;
/* ... */
}
Or 要么
$var = 1;
if ( !foo( $var ) ) echo "Goodbye";
function foo ( $variable ) {
/* Evaluate $variable */
}
By the way, it's almost always better to avoid global variables. 顺便说一句,避免全局变量几乎总是更好。 I would encourage you to go the latter route and pass the value into the function body instead. 我鼓励您采用后一种方法,而是将值传递给函数体。
I strongly recommend you to read Variable scope manual page. 我强烈建议您阅读可变范围手册页。 $var
is invisible for foo()
function, so it is undefined inside of it. $var
对于foo()
函数不可见,因此在其中是未定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.