If we want to instantiate a class that uses a namespace, for example, the Person class and the Animal class are all under namespaceCommon \ Object;, what should we do? You can also write a function to splice the namespace.
It is very easy to instantiate a class in php, such as the instantiation of the Person class:
$obj = new Person();
Sometimes we need to dynamically instantiate an object. for example, there are two classes: the Person class and the Animal class. I need to instantiate the object based on the transmitted parameters. then we can write a function like z:
function get_obj($obj_name){ return new $obj_name();}
If we want to instantiate a class that uses a namespace, for example, the Person class and the Animal class are all under namespace Common \ Object;, what should we do? You can also write a function to splice the namespace:
function get_obj($obj_name){ $obj_name = 'Common\Object\\'.$obj_name; return new $obj_name();}
Of course, we can also use the tired reflection to get an instance. The first two cases are relatively simple. let's stop talking about it and write down the reflection of the last namespace using the class.
function get_obj($obj_name){ $obj_name = 'Common\Object\\'.$obj_name; $class = new \ReflectionClass($obj_name); return $class->newInstance();}