4

I have protected function which creates a class object

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

Now I need to access the methods of the class object from different functions (I don't want to initialise again).

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

How can i get it done?

Oh both the functions exist in the same class say 'class z{}'

The error message is

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

1 Answer 1

3

Store $obj, the instance of classx in a property of ClassZ, probably as a private property. Initialize it in the ClassZ constructor or other initializer method and access it via $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();
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.