Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I dynamically set new object name

Tags:

oop

php

I want to create objects dynamically. Right now I'm creating them manually like this

$obj1 = new Prefix_Myobj();
$obj2 = new Prefix_Other();
$obj3 = new Prefix_Another();

How can I set the part after Prefix_ dynamically? I tried this but it didn't work

$name = 'Myobj';
$obj1 = new Prefix_{$name}();
like image 586
zmol Avatar asked Mar 05 '26 16:03

zmol


1 Answers

You need to create a string that specifies the entire class name.

$name = 'Myobj';
$classname = 'Prefix_'.$name;
$obj1 = new $classname();

However, it might be better design to build a class registry of sorts rather than generating class names on the fly like this.

like image 94
ide Avatar answered Mar 08 '26 08:03

ide



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!