Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php function to unset variables passed by reference

Tags:

php

currently i'm using this php function :

function if_exist(&$argument, $default = '')
{
    if (isset ($argument))
    {
        echo $argument;
    }
    else
    {
        echo $default;
    }
}

i want this function to unset the variables $argument(passed by reference) and $default just after echoing their value, how can i do this? Thanks in advance.

like image 874
Pawan Choudhary Avatar asked Jul 11 '11 18:07

Pawan Choudhary


People also ask

Which function is used to unset variables in PHP?

PHP | unset() Function The unset() function is an inbuilt function in PHP which is used to unset a specified variable.

What does the unset () function do?

unset() destroys the specified variables. 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.

Is PHP pass by value or pass by reference?

Introduction. In PHP, arguments to a function can be passed by value or passed by reference. By default, values of actual arguments are passed by value to formal arguments which become local variables inside the function. Hence, modification to these variables doesn't change value of actual argument variable.

How do you unset multiple values in PHP?

if you see in php documentation there are not available directly remove multiple keys from php array. But we will create our own php custom function and remove all keys by given array value. In this example i created custom function as array_except().


2 Answers

According to the manual for unset:

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.

I assume this is the issue you're encountering. So, my suggestion is to simply set $argument to NULL. Which, according to the NULL docs will "remove the variable and unset its value.".

For example: $argument = NULL;

like image 163
Richard Marskell - Drackir Avatar answered Sep 22 '22 08:09

Richard Marskell - Drackir


$default is passed by value, so it cannot be unset (except in the local scope).

As you undoubtedly discovered, unset() simply unsets the reference to $argument. You can (sort of) unset $argument like this:

$argument = null; 
like image 23
George Cummins Avatar answered Sep 21 '22 08:09

George Cummins