开发者

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

开发者 https://www.devze.com 2023-01-05 07:05 出处:网络
If I want myFunction to take $myVariable and assign to it an instance of SomeClass, I know I can do this:

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开发者_如何学Python { }

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消