Martin Martin - 26 days ago 14
PHP Question

Is it possible to Delete a value passed to a method, from within the method

Say I have a method (which in this particular case is a static method), and this method works on a given value. Once completed is there a way that I can automatically in the code, delete the variable (rather than the function copy).

I suspect from all I've read that this is not possible, but there are no clear declarations of such that my searching has found.

An example case:

Static Method:

public static function checkKey($keyValue = null)
{
if(!is_null($keyValue) && !empty($keyValue)) {
if($_SESSION['keyValue'] == $keyValue) {
unset($keyValue,$_SESSION['keyValue']);
return true;
}
unset($keyValue,$_SESSION['keyValue']);
return false;
}
return false;
}


Usage:

$valueToBeChecked = "I want this value unset from within the function"
//PHP page code
AbstractClass::checkKey($valueToBeChecked);


Is there a way that the method
checkKey
above can delete the value of
$valueToBeChecked
from within the method
checkKey
?

The fact it's a static method shouldn't be too critical, it's more the shape of is there a way that the function can delete a value that is set outside the funtion/method, when passed the variable as a parameter?

I realise this is possible if the whole thing is wrapped in a Class and the variable is saved as a class level variable (
unset($this->var)
), but I'm curious if there's any ability to "reach" variables from outside the scope such as

public static function checkKey($keyValue = null)
{
unset(\$keyValue);
}


I only have limited experience with namespacing but that's my best guess as to if this is possible, how to go about it.

simplified equiviliant outcome:

What I'm trying to reach is this action, entirely within the method:

$valueToBeChecked = "something"
AbstractClass::checkKey($valueToBeChecked);
unset($valueToBeChecked);

Answer

You cannot unset a variable from within a function and have that effect propagate. Per the manual:

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.

However, you can get equivalent behavior through pass-by-reference and setting to null:

function kill(&$value) {
    $value = null;
}

var_dump($x); // NULL
$x = 'foo';
var_dump($x); // 'foo'
kill($x);
var_dump($x); // NULL

This works because, in PHP, there's no distinction made between a symbol that doesn't exist and a symbol that exists with a NULL value.