php注入一个对象然后公开?

时间:2014-08-21 17:45:58

标签: php object dependency-injection public

假设我将php对象“注入”另一个对象,如下所示:

class Customer {
  ...
  function setCustomerLocation(Location $location) {
    $this->location = $location;
  }
  ...
}

我现在如何在客户中制作“注入”位置对象 public ,以便从外部我可以使用自己的公共属性和方法,如下所示(或类似):

$myCustomer->location->getCoordinates();

1 个答案:

答案 0 :(得分:4)

当您动态添加尚未定义为$this->location = $location; 的属性时,默认情况下它是公开的

明确地做:

class Customer {
  public $location;

  function setCustomerLocation(Location $location) {
    $this->location = $location;
  }
}