开发者

Anyone ever used PHP's (unset) casting?

I just noticed PHP has an type casting to (unset), and I'm wondering what it could possibly be used for. It doesn't even really unset the variable, it just casts it to NULL, which means that (unset)$anything should be exactly the same as simply writing NULL.

# Really unsetting the variable results in a notice when accessing it
nadav@shesek:~$ php -r '$foo = 123; unset($foo); echo $foo;'
PHP Notice:  Undefined variable: foo in Command line code on line 1
PHP Stack trace:
PHP   1. {main}() Command line code:0

# (unset) just set it to NULL, and it doesn't result in a notice
nadav@shesek:~$ php -r '$foo = 123; $foo=(unset)$foo; echo $foo;'

Anyone ever used it for anythin开发者_如何学JAVAg? I can't think of any possible usage for it...

Added:

Main idea of question is:

What is reason to use (unset)$smth instead of just NULL?


As far as I can tell, there's really no point to using

$x = (unset)$y;

over

$x = NULL;

The (unset)$y always evaluates to null, and unlike calling unset($y), the cast doesn't affect $y at all.

The only difference is that using the cast will still generate an "undefined variable" notice if $y is not defined.

There's a PHP bug about a related issue. The bug is actually about a (in my mind) misleading passage elsewhere in the documentation which says:

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

And that clearly isn't the case.


I’d guess (knowing PHP and it’s notaribly... interesting choices for different things, I may be completely wrong) that it is so that the value does not need setting to a var. For exact reason to use it for a code, I can’t think of an example, but something like this:

$foo = bar((unset) baz()); 

There you want or need to have null as argument for bar and still needs to call baz() too. Syntax of function has changed and someone did a duck tape fix, like what seems to be hot with PHP.

So I’d say: no reason to use it in well-thought architecture; might be used for solutions that are so obscure that I’d vote against them in first place.


As of PHP 8.0.X, (unset) casting is now removed and cannot be used.


For example it can be used like this

function fallback()
{
    // some stuff here
    return 'zoo';
}

var_dump(false ? 'foo' : fallback()); // zoo
var_dump(false ? 'foo' : (unset) fallback()); // null

Even if fallback() returns "zoo" (unset) will clear that value.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜