当前位置: 动力学知识库 > 问答 > 编程问答 >

PHP: Create a new class object directly from a string return value (string literal)

问题描述:

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();
?>
分享给朋友:
您可能感兴趣的文章:
随机阅读: