Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using methods to access classes and the instantiate them

I have stored the class I want to instantiate in a variable that is accessible via get and set methods:

private $myClass;

public function setClass($myClass) {$this->myClass = $myClass;}
public function getClass() {return $this->myClass;}

Now later on I want to instantiate this class using the get method:

$instance = new $getClass()();

And also work with some of it's static attributes:

$staticAttr = $getClass()::$attr;

But both of these lines throw errors, I think I've found a solution but I'm really not certain and I feel that my problem is some fundamental lack of understand about how to do this. Or perhaps it is just awful practice and so highly discouraged? How best should I go about approaching this?

like image 751
sydan Avatar asked Jan 25 '26 03:01

sydan


2 Answers

PHP's syntax does not allow for this. In order to get this working, you just need to store the class name to a variable first:

$class_name = $obj->getClass();
$instance = new $class_name();

The same goes for accessing the static property:

$class_name = $obj->getClass();
$staticAttr = $class_name::$attr;

This is wrong

$instance = new $getClass()();

Instead do this

$getClass = "classname";

$instance = new $getClass();

for static functions do this

$getClass::getMethod();

For static members

$getClass::$attr;
like image 28
chandresh_cool Avatar answered Jan 26 '26 18:01

chandresh_cool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!