Example analysis of PHP dynamically generating objects based on string class names

Source: Internet
Author: User
in our last lesson PHP security String development ideas and code sharing, we introduced the PHP security string development Use, today we will continue to introduce about PHP string dynamically generated objects, often the need is, from other places to get a name of a class, You need to generate the object for the class, the syntax you used earlier ($obj = new $classname ();) It's definitely not working! Today we will show you how to achieve ~


First download the PHP class library for dynamically generating objects based on the string class name, which we need for this lesson: http://www.php.cn/xiazai/leiku/606


After the download is complete, locate the PHP class library file, unzip it to the local directory, and create a new file ~

We call this class in the new PHP file, and instantiate:

<?phpinclude_once "stringtext.php"; Introduction of Class library file $classname = ' Test ';          $obj = Call_user_func (Array ($className, ' create '); Var_dump ($obj);? >

The direct use of such a grammar is certainly not feasible:

$classname = ' Test '; $obj = new $classname ();

You can define a static method for the target class to generate an instance of the object, and then call the method through Call_user_func or Call_user_func_array. Of course, it can also be implemented by means of factory classes.

So the results of the operation are as follows:

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.