Home > Article > Backend Development > Example analysis of php dynamically generating objects based on string class names
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
<?php include_once "stringtext.php"; //引入类库文件 $className = 'Test'; $obj = call_user_func(array($className, 'create')); var_dump($obj); ?>It will definitely not work if you use such syntax directly:
$classname='Test'; $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.
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!