[PHP 4, PHP 5, PHP 7, PHP 8]
unset — Unset a given variable
Description
The behavior of unset[] inside of a function can vary depending on what type of variable you are attempting to destroy.
If a globalized variable is unset[] inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset[] was called.
The above example will output:
To unset[] a global variable inside of a function, then use the $GLOBALS array to do so:
If a variable that is PASSED BY REFERENCE is unset[] inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset[] was called.
The above example will output:
If a static variable is unset[] inside of a function, unset[] destroys the variable only in the context of the rest of a function. Following calls will restore the previous value of a variable.
The above example will output:
Before unset: 1, after unset: 23 Before unset: 2, after unset: 23 Before unset: 3, after unset: 23
Parameters
var
The variable to be unset.
vars
Further variables.
Return Values
No value is returned.
Examples
Example #1 unset[] example
Example #2 Using [unset]
casting
[unset]
casting is often confused with the unset[] function. [unset]
casting serves only as a NULL
-type cast, for completeness.
It does not alter the variable it's casting. The [unset] cast is deprecated as of PHP 7.2.0, removed as of 8.0.0.
The above example will output:
Notes
Note: Because this is a language construct and not a function, it cannot be called using variable functions, or named arguments.
Note:
It is possible to unset even object properties visible in current context.
Note:
It is not possible to unset
$this
inside an object method.
Note:
When using unset[] on inaccessible object properties, the __unset[] overloading method will be called, if declared.
See Also
- isset[] - Determine if a variable is declared and is different than null
- empty[] - Determine whether a variable is empty
- __unset[]
- array_splice[] - Remove a portion of the array and replace it with something else
- [unset] casting
Hayley Watson ¶
9 years ago
You don't need to check that a variable is set before you unset it.
is harmless.
is pointless complication.
This doesn't apply to properties of objects that have __isset[] methods that visibly change object state or __unset[] methods that don't properly check their arguments or have extra side effects.
The latter case means that __unset shouldn't do more than what it says on the tin, and also has the responsibility for checking [possibly using __isset[]] that what it's being asked to do makes sense.
The former case is just plain bad design.
nox at oreigon dot de ¶
14 years ago
if you try to unset an object, please be careful about references.
Objects will only free their resources and trigger their __destruct method when *all* references are unsetted.
Even when they are *in* the object... sigh!