What is the purpose of unset as cast in PHP?

3

As of PHP 5, there is a way to cast a cast to convert a given value to NULL .

Example:

$teste = 'teste';

var_dump((unset)$teste); // NULL

$outroTeste = (unset) funcao();

var_dump($outroTeste); // NULL

I can understand that unset($var) destroys the variable, however (unset) $var is an expression to convert it to NULL

But finally:

  • What is the purpose of this implementation - unset as cast?

  • $var = NULL; would not be enough?

  • Is there a case where casting would be important for unset (unset) ?

asked by anonymous 12.12.2014 / 02:50

2 answers

3
  

What is the purpose of this implementation?

As explained by Pope Charlie , it uses the type-conversion syntax to generate a null value. In the language it is possible to do casting for any primitive language type, such as strings and numbers, including type null . It's strange, but less strange to choose the syntax (unset) instead of (null) .

  

$var = NULL ; would not it be enough?

It would be, using% literal% is enough in most cases.

  

Is there a case where it would be important to use null ?

"Important" would be too strong a term, but a subject in the SO in English claims to use this to "undock a string of conditionals a>, applying on the return of a function, and as part of a conditional expression.

    
16.12.2014 / 03:17
4
  

What is the purpose of this implementation?

I think you're referring to (unset) $var usage. This way is related to typing the variable, such as (int) $var , or (string) $var ... the use of (unset) $var will change the type of the variable to null .

Casting a variable to null using (unset) $var will not remove the variable or unset its value ( DOC )

  

$var = NULL would not be enough?

There are times when you may need to destroy a variable and not simply have it as null, and by using $var = NULL , $ var will continue to exist. However, to change type , yes, $var = NULL might suffice since it has the same effect as (unset) $var .

However, if you maintain a typing pattern, using (unset) $var may be more convenient than $var = NULL , because in the second case you are changing the type by assigning a new value by rewriting the variable.

An example:

#1
$var = (int)'123'

#2
$var = 123

In both cases my $ var is an int type. In the first one I forced the typing of string to integer and in the second it assigns an integer value.

  

Is there a case where it would be important to use (unset) ?

About this there is a lot of explanation on the DOC function, but I do not know if you mean (unset) $var typing or the removal of the variable with unset( $var ) .

I do not know if that was exactly what you wanted to know, it was not very clear if the function or the typing was left over. If I need to, I'll try to upgrade.

    
12.12.2014 / 10:23