从函数中调用PHP对象方法

时间:2012-07-16 17:54:40

标签: php class function object methods

我有保护功能,可以创建一个类对象

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

1 个答案:

答案 0 :(得分:3)

$obj的实例classx存储在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();
  }
}