4

我有创建类对象的受保护函数

protected function x() {
    $obj = new classx();
}

现在我需要从不同的函数访问类对象的方法(我不想再次初始化)。

protected function y() {
    $objmethod = $obj->methodx();
}

我怎样才能完成它?

哦,这两个函数都存在于同一个类中说'class z{}'

错误信息是

Fatal error: Call to a member function get_verification() on a non-object in
4

1 回答 1

3

Store , 的一个属性中$obj的实例,可能作为一个属性。在构造函数或其他初始化方法中对其进行初始化,并通过.classxClassZprivateClassZ$this->obj

class ClassZ {
  // Private property will hold the object
  private $obj;

    // Build the classx instance in the constructor
  public function __construct() {
    $this->obj = new ClassX();
  }

  // Access via $this->obj in other methods
  // Assumes already instantiated in the constructor
  protected function y() {
    $objmethod = $this->obj->methodx();
  }

  // If you don't want it instantiated in the constructor....

  // You can instantiate it in a different method than the constructor
  // if you otherwise ensure that that method is called before the one that uses it:
  protected function x() {
    // Instantiate
    $this->obj = new ClassX();
  }

  // So if you instantiated it in $this->x(), other methods should check if it
  // has been instantiated
  protected function yy() {
    if (!$this->obj instanceof classx) {
      // Call $this->x() to build $this->obj if not already done...
      $this->x();
    }
    $objmethod = $this->obj->methodx();
  }
}
于 2012-07-16T17:58:54.573 回答