为什么变量在 if 块内为空,但在其外部有值?
Why is the variable empty inside an if block, but has a value outside of it?
我发现了一些我无法解释的东西。 $post_id
设置为9
,$bookmarks
是一个数组,里面有[5] => true
。如果我将 die($post_id)
移到此块之外并且 没关系 如果我将它放在 之前或之后 , $post_id
将包含 9
但在块内它既没有类型也没有值。怎么可能?
if ( !array_key_exists($post_id, $bookmarks) ) {
$bookmarks[$post_id] = true;
die($post_id);
}
UPD:我已经编辑了代码,现在应该不会让您感到困惑了。
die()
与 exit()
和 according to the PHP Manual 相同,exit()
有两种不同的行为:
void exit ([ string $status ] )
void exit ( int $status )
说明:
If status is a string, this function prints the status just before
exiting.
If status is an integer, that value will be used as the exit status
and not printed. Exit statuses should be in the range 0 to 254, the
exit status 255 is reserved by PHP and shall not be used. The status 0
is used to terminate the program successfully.
因为 $post_id
是一个整数,die($post_id)
实际上不会打印任何内容,而只会修改进程的退出代码。
您可以 die()
通过将数字重铸为字符串来打印数字:
die(strval($post_id));
我发现了一些我无法解释的东西。 $post_id
设置为9
,$bookmarks
是一个数组,里面有[5] => true
。如果我将 die($post_id)
移到此块之外并且 没关系 如果我将它放在 之前或之后 , $post_id
将包含 9
但在块内它既没有类型也没有值。怎么可能?
if ( !array_key_exists($post_id, $bookmarks) ) {
$bookmarks[$post_id] = true;
die($post_id);
}
UPD:我已经编辑了代码,现在应该不会让您感到困惑了。
die()
与 exit()
和 according to the PHP Manual 相同,exit()
有两种不同的行为:
void exit ([ string $status ] )
void exit ( int $status )
说明:
If status is a string, this function prints the status just before exiting.
If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.
因为 $post_id
是一个整数,die($post_id)
实际上不会打印任何内容,而只会修改进程的退出代码。
您可以 die()
通过将数字重铸为字符串来打印数字:
die(strval($post_id));