我需要检查值是否定义为任何值,包括null。 isset
将null值视为undefined并返回false
。以下面的例子为例:
$foo = null;
if(isset($foo)) // returns false
if(isset($bar)) // returns false
if(isset($foo) || is_null($foo)) // returns true
if(isset($bar) || is_null($bar)) // returns true, raises a notice
请注意,$bar
未定义。
我需要找到满足以下条件的条件:
if(something($bar)) // returns false;
if(something($foo)) // returns true;
有任何想法吗?
IIRC,您可以使用get_defined_vars()
:
$foo = NULL;
$vars = get_defined_vars();
if (array_key_exists('bar', $vars)) {}; // Should evaluate to FALSE
if (array_key_exists('foo', $vars)) {}; // Should evaluate to TRUE
如果您正在处理可能具有NULL值的对象属性,则可以使用:property_exists()
而不是isset()
<?php
class myClass {
public $mine;
private $xpto;
static protected $test;
function test() {
var_dump(property_exists($this, 'xpto')); //true
}
}
var_dump(property_exists('myClass', 'mine')); //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto')); //true, as of PHP 5.3.0
var_dump(property_exists('myClass', 'bar')); //false
var_dump(property_exists('myClass', 'test')); //true, as of PHP 5.3.0
myClass::test();
?>
与isset()相反,即使属性值为NULL,property_exists()也返回TRUE。
见Best way to test for a variable's existence in PHP; isset() is clearly broken
if( array_key_exists('foo', $GLOBALS) && is_null($foo)) // true & true => true
if( array_key_exists('bar', $GLOBALS) && is_null($bar)) // false & => false
我发现compact
是一个忽略未设置变量的函数,但确实对设置为null
的函数起作用,所以当你有一个大的局部符号表时,我想你可以通过使用array_key_exists('foo', get_defined_vars())
来检查array_key_exists('foo', compact('foo'))
更有效的解决方案:
$foo = null;
echo isset($foo) ? 'true' : 'false'; // false
echo array_key_exists('foo', compact('foo')) ? 'true' : 'false'; // true
echo isset($bar) ? 'true' : 'false'; // false
echo array_key_exists('bar', compact('bar')) ? 'true' : 'false'; // false
更新
从PHP 7.3开始,compact()将发布未设置值的通知,因此不幸的是,此替代方案已不再有效。
如果给定的字符串引用未设置的变量,compact()现在会发出E_NOTICE级别错误。以前,这些字符串已被默默跳过。
以下编写为PHP扩展的代码等同于array_key_exists($ name,get_defined_vars())(感谢Henrik和Hannes)。
// get_defined_vars()
// https://github.com/php/php-src/blob/master/Zend/zend_builtin_functions.c#L1777
// array_key_exists
// https://github.com/php/php-src/blob/master/ext/standard/array.c#L4393
PHP_FUNCTION(is_defined_var)
{
char *name;
int name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) {
return;
}
if (!EG(active_symbol_table)) {
zend_rebuild_symbol_table(TSRMLS_C);
}
if (zend_symtable_exists(EG(active_symbol_table), name, name_len + 1)) {
RETURN_TRUE;
}
}
这里有一些使用xdebug的愚蠢的解决方法。 ;-)
function is_declared($name) {
ob_start();
xdebug_debug_zval($name);
$content = ob_get_clean();
return !empty($content);
}
$foo = null;
var_dump(is_declared('foo')); // -> true
$bla = 'bla';
var_dump(is_declared('bla')); // -> true
var_dump(is_declared('bar')); // -> false
is_null($bar)
返回true,因为它根本没有值。或者,您可以使用:
if(isset($bar) && is_null($bar)) // returns false
检查$bar
是否已定义,并且仅在以下情况下返回true:
$bar = null;
if(isset($bar) && is_null($bar)) // returns true