Is it possible to pass parameters by reference using call_user_func_array()?

前端 未结 4 1441
情话喂你
情话喂你 2020-11-29 05:46

When using call_user_func_array() I want to pass a parameter by reference. How would I do this. For example

function toBeCalled( &$paramet         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 06:27

    Directly, it may be impossible -- however, if you have control both over the function you are implementing and of the code that calls it - then there is one work-around that you might find suitable.

    Would you be okay with having to embed the variable in question into an object? The code would look (somewhat) like this if you did so.

    function toBeCalled( $par_ref ) {
        $parameter = $par_ref->parameter;
        //...Do Something...
        $par_ref->parameter = $parameter;
    }
    
    $changingVar = 'passThis';
    $parembed = new stdClass; // Creates an empty object
    $parembed->parameter = array( $changingVar );
    call_user_func_array( 'toBeCalled', $parembed );
    

    You see, an object variable in PHP is merely a reference to the contents of the object --- so if you pass an object to a function, any changes that the function makes to the content of the object will be reflected in what the calling function has access to as well.

    Just make sure that the calling function never does an assignment to the object variable itself - or that will cause the function to, basically, lose the reference. Any assignment statement the function makes must be strictly to the contents of the object.

提交回复
热议问题