更正 PHP 代码以检查变量是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5852094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct PHP code to check if a variable exists
提问by JJJollyjim
This code is part of a websocket server:
此代码是 websocket 服务器的一部分:
$msgArray = json_decode($msg);
if ($msgArray->sciID) {
echo "Has sciID";
}
It will either be receiving a json string like {"sciID":67812343}or a completely different json string with no sciID such as {"something":"else"}.
它将接收类似 json 字符串{"sciID":67812343}或完全不同的没有 sciID 的 json 字符串,例如{"something":"else"}.
When the server receives the later, it echos out: Notice: Undefined property: stdClass::$sciID in /path/to/file.php on line 10
当服务器接收到后者时,它会回显: Notice: Undefined property: stdClass::$sciID in /path/to/file.php on line 10
What is the correct code to check if $msgArray->sciIDexists?
检查是否$msgArray->sciID存在的正确代码是什么?
回答by Ross
Use issetas a general purpose check (you could also use property_existssince you're dealing with an object):
使用isset作为通用支票(你也可以使用property_exists,因为你正在处理的对象):
if (isset($msgArray->sciID)) {
echo "Has sciID";
}
回答by Oliver Charlesworth
回答by Petr Hurtak
In case isset()or property_exists()doesn't work, we can use array_key_exists()
万一isset()或property_exists()不起作用,我们可以使用array_key_exists()
if (array_key_exists("key", $array)) {
echo "Has key";
}
回答by Joshwaa
I've always done isset()but I've recently changed to !empty()and emptybecause one of my friends suggested it.
我一直这样做,isset()但我最近改为!empty()并且empty因为我的一位朋友建议这样做。
回答by Sophivorus
The isset()function checks if a variable is set and is not null, which is really stupid, given its name. If you only want to know if a variable is set, use the following function:
该isset()函数检查变量是否已设置并且不为 null,鉴于其名称,这真的很愚蠢。如果您只想知道是否设置了变量,请使用以下函数:
function is_set( & $variable ) {
if ( isset( $variable ) and ! is_null( $variable ) )
return true;
else
return false;
}
This function will return true exactly when the variable is not set, and false otherwise. The '&' next to the argument is important, because it tells PHP to pass a referenceto the variable, and not the valueof the variable, thus avoiding a "Notice:Undefined variable" when the variable is not set.
当变量未设置时,此函数将返回 true,否则返回 false。参数旁边的 '&' 很重要,因为它告诉 PHP 传递对变量的引用,而不是变量的值,从而避免在未设置变量时出现“注意:未定义变量”。

