破坏构造函数 [英] Breaking the constructor
问题描述
有没有一种方法可以防止在其构造函数中创建对象,因此:
Is there a way to prevent object creation within its constructor, so that:
$object = new Foo();
echo $object; // outputs: NULL
推荐答案
不是,不可能;不能. new
关键字始终会返回指定类的实例,无论您尝试从构造方法中返回什么.这是因为到构造函数被调用时,PHP已经为新对象完成了内存分配.换句话说,那时该对象已经存在(否则,根本没有对象可以调用构造函数).
Nope, not possible; the new
keyword always returns an instance of the class specified, no matter what you attempt to return from the constructor. This is because by the time your constructor is called, PHP has already finished allocating memory for the new object. In other words, the object already exists at that point (otherwise, there's no object on which to call the constructor at all).
您可以从构造函数中引发错误或引发异常,然后相应地进行处理.
You could raise errors or throw exceptions from the constructor instead, and handle those accordingly.
class Foo {
public function __construct() {
throw new Exception('Could not finish constructing');
}
}
try {
$object = new Foo();
} catch (Exception $e) {
echo $e->getMessage();
}
这篇关于破坏构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!