Calling PHP object methods from functions

12,080

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();
  }
}
Share:
12,080
Abhishek Salian
Author by

Abhishek Salian

merge delete

Updated on June 04, 2022

Comments

  • Abhishek Salian
    Abhishek Salian almost 2 years

    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