简体   繁体   中英

Is it possible to pass a variable stored in an array by reference in PHP?

If I want myFunction to take $myVariable and assign to it an instance of SomeClass , I know I can do this:

class SomeClass { }

function myFunction(&$myVariable) {
    $myVariable = new SomeClass();
}

myFunction($myVariable);

var_dump($myVariable);

However, I would like to be able to have myFunction operate like this:

class SomeClass { }

function myFunction($args = array()) {
    if(isset($args['something'])) {
        $$args['something'] = new SomeClass();
    }
}

myFunction(array(
    'something' => $myVariable
));

var_dump($myVariable);

Is there any way to achieve this?

it's an ugly hack but could work:

 global $$args['something'];
 $$args['something'] = new SomeClass();

But you should never introduce such side effects.

You can only pass variables by reference, so

myFunction(array()) 

will not work in either case.

Im not sure what your doing, but lets say

$myVariable = 'Mary';
$array['something'] = $myVariable;

Then

$$array['something'] === $Mary

Which doesnt exist.

I havent tested it, but I dont think that will work the way you want it to, even with global variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM