开发者

PHP: Cast variable to null

I just stumbled upon a thing in the PHP manual that is new to me...

Casting a variable to null will remove the variable and unset its value. (Source)

Now I wonder how this can be done... I tried (null) and (NULL) but it seems to be interpreted as the value null, not the type null. I know this question must sound ridiculous, but does somebody know how 开发者_开发技巧to cast to null?


Update: Since posting this 9 years ago, casting to unset has changed behavior and is deprecated. The last defined behavior was equivalent to setting the variable equal to NULL. You can either set the variable equal to NULL to retain the variable but indicate it has no value, or you can call the unset function to remove it entirely.

Original Answer:

$a = (unset) $a;

See type casting.


use (unset) instead of (null).


According to the Type casting section of the Type Juggling manual page, you can achieve this via...

$varName = (unset)$varName;


You can cast a variable to null, as in the following example, but this behavior is deprecated in PHP 7.2 so you shouldn’t do it even though PHP 7.1 supports it.

$a = "Hello World";
$a = (unset)$a; // Deprecated in PHP 7.2
var_dump($a);   // NULL


This piece of code is meant, isset will return false.

$test = "a";
$test = null;
var_dump( isset( $test ));

Casting variables in PHP is done by assigning it specific value ( eg $foo = intval( $bar ) etc. ). If you put NULL into variable it will be interpreted as NULL ( type NULL ), isset return false if variable is type NULL

Edit: if you want to completly unset variable use

unset( $test );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜