No, I'm not referring to the unset() language construct, but the (unset) type caster. From the PHP manual:
The casts allowed are:
- (int), (integer) - cast to integer
- (bool), (boolean) - cast to boolean
- (float), (double), (real) - cast to float
- (string) - cast to string
- (array) - cast to array
- (object) - cast to object
- (unset) - cast to NULL (PHP 5)
URL: http://php.net/manual/en/language.types.type-juggling.php
Does anyone have any idea about this (or even used it in an actual project)?
I didn't even know this was a thing, but it seems like the purpose is just completeness for available php primitives (NULL being one of them). Note that this casts the data .. it does not do a write.
$x = 'foon';
$y = (unset)$x;
var_dump($x, $y) // 'foon', NULL
Note that x
is not null
in spite of the cast.
Near as I can tell, there's no reason to ever use (unset)<anything>
as opposed to just writing NULL
. Perhaps someone else can come up with a better answer, though.
I use (unset)
casting to avoid creating ugly if
else
statements in situation if you need to validate and use many variables, but if one variable is considered incorrect and you do not want to check remaining.
For example, you have following code:
$variableone = "ffo";
$variabletwo = "obb";
$variablethree = "aar";
if(checkonefailed($variableone))
{
outputsomething();
}
else
{
dosomething($variableone)
if(checktwofailed($variabletwo))
{
outputsomething();
}
else
{
dosomething($variabletwo)
if(checkthreefailed($variablethree))
{
outputsomething();
}
else
{
dosomething($variablethree)
//And so own
}
}
}
You can rewrite it like this:
$variableone = "ffo";
$variabletwo = "obb";
$variablethree = "aar";
if(checkonefailed($variableone))
{
outputsomething();
}
//False or check
elseif((unset)(dosomething($variableone))||(checktwofailed($variabletwo)))
{
outputsomething();
}
elseif((unset)(dosomething($variabletwo))||(checkthreefailed($variablethree)))
{
outputsomething();
}
elseif((unset)(dosomething($variablethree))/*or next variable*/)
{
//And so own
}
Idea taken from Go programming code
if variableone := "ffo"; checkonefailed(variableone) {
outputsomething()
} else if dosomething(variableone); variabletwo := "obb"; checktwofailed(variabletwo) {
outputsomething()
} else if dosomething(variabletwo); variablethree := "aar"; checkthreefailed(variablethree) {
outputsomething()
} else dosomething(variablethree)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With