Answers:
是的你可以!
$str = 'One';
$class = 'Class'.$str;
$object = new $class();
使用名称空间时,请提供标准名称:
$class = '\Foo\Bar\MyClass';
$instance = new $class();
您可以在php中执行的其他一些很酷的操作是:
变量变量:
$personCount = 123;
$varname = 'personCount';
echo $$varname; // echo's 123
以及可变的函数和方法。
$func = 'my_function';
$func('param1'); // calls my_function('param1');
$method = 'doStuff';
$object = new MyClass();
$object->$method(); // calls the MyClass->doStuff() method.
$my_obj = Package\$class_name();
。相反,您必须$class_name = "Package\\" . $class_name; $my_obj = new $class_name();
$className = '\Foo\Bar\MyClass';
$instance = new $className();
$model = $user_model::find()->All();
在哪里$user_model
您可以简单地使用以下语法来创建新类(如果您正在创建factory,这将很方便):
$className = $whatever;
$object = new $className;
作为(异常粗糙的)示例工厂方法:
public function &factory($className) {
require_once($className . '.php');
if(class_exists($className)) return new $className;
die('Cannot create new "' . $className . '" class - includes not found or class unavailable.');
}
require_once($className.'php');
->require_once($className.'.php');
看一下http://www.php.net/manual/en/language.oop5.basic.php中的示例3
$className = 'Foo';
$instance = new $className(); // Foo()
可以说ClassOne
定义为:
public class ClassOne
{
protected $arg1;
protected $arg2;
//Contructor
public function __construct($arg1, $arg2)
{
$this->arg1 = $arg1;
$this->arg2 = $arg2;
}
public function echoArgOne
{
echo $this->arg1;
}
}
使用PHP反射;
$str = "One";
$className = "Class".$str;
$class = new \ReflectionClass($className);
创建一个新实例:
$instance = $class->newInstanceArgs(["Banana", "Apple")]);
调用方法:
$instance->echoArgOne();
//prints "Banana"
使用变量作为方法:
$method = "echoArgOne";
$instance->$method();
//prints "Banana"
使用Reflection而不是仅使用原始字符串来创建对象,可以使您更好地控制对象并简化可测试性(PHPUnit高度依赖Reflection)