Calling PHP Object Methods from Functions

I have a protected function that 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 do not want to initialize again).

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

How can i do this?

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

Error message

 Fatal error: Call to a member function get_verification() on a non-object in 
+4
source share
1 answer

Store $obj , an instance of classx in the classx property, possibly as a private property. Initialize it in the ClassZ constructor or other initialization 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(); } } 
+3
source

All Articles