从函数调用PHP对象方法


Calling PHP object methods from functions

我有一个受保护的函数,它创建了一个类对象

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

$objclassx的实例存储在ClassZ的属性中,可能作为private属性。在ClassZ构造函数或其他初始化器方法中初始化它,并通过$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();
  }
}