PHP dynamic instantiation of a namespace class object several methods

Source: Internet
Author: User
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();}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.