PHP param by ref => assign to ref = NULL

后端 未结 1 1044
野趣味
野趣味 2020-12-21 20:21

I found a strange behavior when passing parameter by reference to an object method:

class Test
{
    private $value;
    public  function Set($value)
    {
          


        
相关标签:
1条回答
  • 2020-12-21 20:59

    You are assigning to a reference by reference. This is why you get null. It works fine if you assign normally:

    public function GetByRef(&$ref) {
        $ref = $this->value;
    }
    

    By declaring &$ref in the method signature and calling the method, a variable is created in the calling scope with a default value of null, which is referenced inside the method as $ref. By doing $ref = &$this->value you are basically removing that reference and are creating a new reference $ref. Using =& always creates a new reference variable; if you want to change its value instead, you have to use = to assign to it. So the variable which was created in the calling scope remains set at its initial value null and its reference to $ref inside the method is broken.

    0 讨论(0)
提交回复
热议问题