未定义是 php 中的数据类型吗? [英] Is undefined a data-type in php?
问题描述
undefined
是 php 中的数据类型吗?另外,如何检查它(在变量上,是否未定义)?
Is undefined
a data-type in php?
Also, how does one check for it (on a variable, is or is not undefined)?
推荐答案
PHP 中没有未定义"的数据类型.您可以检查使用 isset
设置的变量,但这无法区分根本没有设置的变量和它具有 null
值:
There is no "undefined" data type in PHP. You can check for a variable being set with isset
, but this cannot distinguish between a variable not being set at all and it having a null
value:
var_dump(isset($noSuchVariable)); // false
$nullVariable = null;
var_dump(isset($nullVariable)); // also false
但是,有一个技巧可以用于 compact
允许您确定变量是否已定义,即使其值为 null
:
However, there is a trick you can use with compact
that allows you to determine if a variable has been defined, even if its value is null
:
var_dump(!!compact('noSuchVariable')); // false
var_dump(!!compact('nullVariable')); // true
现场示例.
isset
和 compact
技巧也同时适用于多个变量(使用逗号分隔的列表).
Both isset
and the compact
trick also work for multiple variables at once (use a comma-separated list).
在处理数组键时,您可以轻松区分 null
值和完全不存在:
You can easily distinguish between a null
value and total absence when dealing with array keys:
$array = array('nullKey' => null);
var_dump(isset($array['nullKey'])); // false
var_dump(array_key_exists($array, 'nullKey')); // true
现场示例.
在处理对象属性时,还有 property_exists
,相当于对象的array_key_exists
.
When dealing with object properties there is also property_exists
, which is the equivalent of array_key_exists
for objects.
这篇关于未定义是 php 中的数据类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!