Abhishek Salian
Abhishek Salian

Reputation: 934

Calling PHP object methods from functions

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

Upvotes: 4

Views: 14897

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270609

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();
  }
}

Upvotes: 3

Related Questions