Saturday, 14 December 2019

PHP Returning an object from a function




My problem is this (In PHP):




I have three classes,



Class cls1 {
public function myfunc() {

}
}
Class cls2 {
private $_obj1; //type of cls1
...

public function getObj1() {
return $_obj1;
}
}

Class cls3 {
...
public function getMyFunc() {
$temp = new cls2();
$temp->getObj1()->myfunc(); //THIS IS NOT WORKING.

//PHP Throws an error like : Fatal error: Call to a member function getId() on a non-object in xyz.php on line 125.
}
}


I cannot reach cls1's function from cls3 through the way cls2.



How can I implement it?



NOTE: I wrote this basic code to show the problem. Do not consider about syntax errors.



Answer



Object1 hasn't been instantiated yet.



Class cls1 {
public function myfunc() {

}
}
Class cls2 {
private $_obj1; //type of cls1

...
public function getObj1() {
if(!$this->$_obj1 instanceof cls1) {
$this->_obj = new cls1();
}
return $_obj1;
}
}

Class cls3 {

...
public function getMyFunc() {
$temp = new cls2();
$temp->getObj1()->myfunc(); //THIS IS NOT WORKING.
}
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...