Home  >  Article  >  Backend Development  >  Example analysis of php dynamically generating objects based on string class names

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

黄舟
黄舟Original
2017-08-15 14:36:194903browse

In our last lessonDevelopment Ideas and Code Sharing of PHP Safe Strings, we introduced the development and use of PHP safe strings. Today we will continue to introduce it to you. Regarding the dynamic generation of objects from PHP strings, a common requirement is to obtain the name of a class from other places and need to generate an object of that class. Then the syntax used before ($obj = new $classname();) will definitely not work. ! Today we will introduce to you how to achieve~


##Download first The PHP class library we need to use in this lesson is to dynamically generate objects based on string class names: http://www.php.cn/xiazai/leiku/606


After the download is complete, find the php class library file, extract it to the local directory, and then create a new file~

We are in the new Calling this class in the php file and instantiating it:

<?php
include_once "stringtext.php"; //引入类库文件
$className = &#39;Test&#39;;          
$obj = call_user_func(array($className, &#39;create&#39;));

var_dump($obj);
?>

It will definitely not work if you use such syntax directly:


$classname=&#39;Test&#39;;
$obj = new $classname();

You can define a static method for the target class to generate the instance of the object and then call the method via call_user_func or call_user_func_array. Of course, it can also be implemented through methods such as factory classes.


So the running result is as follows:

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

The above is the detailed content of Example analysis of php dynamically generating objects based on string class names. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn