I would create my own personalized unset function but it does not work. Here is an example of code that does not work.
<?php
function remove_var($mixedVar)
{
unset($mixedVar);
}
$sExample='Php';
remove_var($sExample);
echo $sExample;
?>
I would create my own personalized unset function but it does not work. Here is an example of code that does not work.
<?php
function remove_var($mixedVar)
{
unset($mixedVar);
}
$sExample='Php';
remove_var($sExample);
echo $sExample;
?>
Your function won't unset $sExample
because it exists outside of that function. Wonder why don't you use unset
instead.
function remove_var($mixedVar)
{
unset($mixedVar); // $mixedVar is unset not actual variable
}
$sExample='Php'; // this is outside variable
remove_var($sExample);
echo $sExample;
Even if you pass variable by reference, the unset
won't remove that variable. For example:
function remove_var(&$mixedVar)
{
unset($mixedVar);
}
$sExample='Php';
remove_var($sExample);
echo $sExample; // Php
So you should use unset
instead.
The first issue is that you're passing the argument by value, so what you do to it within remove_var()
doesn't affect the original variable, outside the function. To pass by reference instead, change the function declaration as follows:
function remove_var(&$mixedVar)
However, there's still a quirk using unset()
this way -- it doesn't work for me, even when the variable is passed by reference. However, it does work if you set the variable to null
instead, which is mostly equivalent. When the variable in the function is unset()
, it removes that reference but leaves the original reference and doesn't change the value. When you change the value to null
instead, the references are left alone but the value is obviously changed to null
. Since getting the value of an unset variable gives you null
anyway, that should be effectively equivalent. So try:
function remove_var(&$mixedVar)
{
$mixedVar = null;
}