Is there any possibility to create a new object by a string that is returned by a function or method in PHP? Like some escape method I do not know?
Non-working example:
new ($class->method())();
new "stringliteral"();
new ($class = $class->method())();
You can do it using ReflectionClass
function makeRef($className) {
return new ReflectionClass($className);
}
$obj = makeRef($class->method())->newInstance();
In PHP 5.4+ you can turn this into a one-liner:
$obj = (new ReflectionClass($class->method()))->newInstance();
Do you want dynamic class creation? here is a read : http://docstore.mik.ua/orelly/webprog/pcook/ch07_13.htm
While it is OK to invoke dynamic function, doing it for class seems to be a stunt.
Yes it is possible. Assign the string to a variable then create object using that variable.
Ex.
<?php
class stringliteral{
function __construct()
{
echo"called";
}
}
function dumyFunc()
{
return 'stringliteral';
}
$str=dumyFunc();
if(class_exists($str))
$obj=new $str();
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.