在Javascript中,我可以动态引用和使用构造函数:
function Circle() {
}
function Squere() {
}
var constructor = null;
constructor = Circle;
var shape1 = new constructor();
console.log(shape1 instanceof Circle); // output: true
constructor = Squere;
var shape2 = new constructor();
console.log(shape2 instanceof Squere); // output: true这是可能的吗?我如何在php中做到这一点呢?我如何在php中获取类声明并动态引用和使用它,这样调用代码就不知道/不关心它正在创建什么?
发布于 2015-01-31 12:20:23
在PHP中,不能传递类(或其构造函数)本身,但它的名称:
class Circle { /* ... */ }
class Square { /* ... */ }
$classname = 'Circle';
$shape1 = new $classname();
// $shape1 is now a Circlehttps://stackoverflow.com/questions/28251478
复制相似问题