Can I dynamically set a new object name

I want to dynamically create objects. 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 item after Prefix_dynamic? I tried this, but it did not work.

$name = 'Myobj';
$obj1 = new Prefix_{$name}();
+3
source share
3 answers

You need to create a string defining the fully qualified name of the class.

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

However, it might be better to construct a class registry construct rather than generate class names on the fly like this.

+9
source

Why do you need this? There may be a better solution to your problem; multi-ton or dependent injections, etc.

0
source

It is important to say that if your class is in a specific namespace, you need to tell the full path. Example:

namespace my\path\app;

class MyClass {

    $name = 'Myobj';
    $classname = 'my\path\app\Prefix_' . $name;
    $obj1 = new $classname();
}
0
source

Source: https://habr.com/ru/post/1790530/


All Articles