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

$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();
  }
}
于 2012-07-16T17:58:54.573 に答える