Is there ever a need to use ampersand in front of an object?

两盒软妹~` 提交于 2020-01-11 05:15:48

问题


Since objects are passed by reference by default now, is there maybe some special case when &$obj would make sense?


回答1:


Objects use a different reference mechanism. &$object is more a reference of a reference. You can't really compare them both. See Objects and references:

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

&$object is something else than $object. I'll give you an example:

foreach ($objects as $object) {
    if ($cond) {
        $object = new Object(); // This won't affect $objects

    }
}

foreach ($objects as &$object) {
    if ($cond) {
        $object = new Object(); // This will affect $objects

    }
}

I won't answer the question if it makes sense, or if there is a need. These are opinion based questions. You can definitely live without the & reference on objects, as you could without objects at all. The existence of two mechanisms is a consequence of PHP's backward compatibility.




回答2:


There are situations where you add & in front of function name, to return any value as a reference.

To call those function we need to add & in front of object.

If we add & in front of object, then it will return value as reference otherwise it will only return a copy of that variable.

class Fruit() {

    protected $intOrderNum = 10;

    public function &getOrderNum() {
        return $this->intOrderNum;
    }
}

class Fruitbox() {

   public function TestFruit() {
      $objFruit = new Fruit();
      echo "Check fruit order num : " . $objFruit->getOrderNum(); // 10

      $intOrderNumber = $objFruit->getOrderNum();
      $intOrderNumber++;
      echo "Check fruit order num : " . $objFruit->getOrderNum(); // 10

      $intOrderNumber = &$objFruit->getOrderNum();
      $intOrderNumber++;
      echo "Check fruit order num : " . $objFruit->getOrderNum(); // 11
   }    
}


来源:https://stackoverflow.com/questions/21058439/is-there-ever-a-need-to-use-ampersand-in-front-of-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!