我有两个类,"A"和"B"。在应用逻辑中,除了类"A",任何人都不允许创建类"B"的对象。
但是,由于我不想把这两个类放在同一个文件中,所以无法使用“private”属性进行限制。
是否可能创建这种限制?如果除了"A"之外的其他人尝试创建类"B"的对象,您可以说“滚开!”吗?
是否可能创建这种限制?如果除了"A"之外的其他人尝试创建类"B"的对象,您可以说“滚开!”吗?
这是非常不规范的做法,您不应该使用它。我只是发布它,因为我喜欢非常规的东西 ;) 此外,如果启用了E_STRICT
错误报告,则会抛出错误:
class B
{
private function __construct() {}
public function getInstance() {
if (!isset($this) || !$this instanceof A) {
throw new LogicException('Construction of B from a class other than A is not permitted.');
}
return new self;
}
}
class A
{
function someMethod() {
$b = B::getInstance(); // note that I'm calling the non-static method statically!
}
}
E_STRICT
错误。 - BoltClockerror_reporting(-1)
并使用@$b = B::getInstance();
,但我不确定@
是否会抑制在getInstance方法中生成的所有警告/错误。 - Sudhi您可以检查回溯:
class B
{
public function __construct()
{
$chain = debug_backtrace();
$caller = $chain[1]['class'];
if ('A' != $caller) {
throw new Exception('Illegal instantiation');
}
}
}
class A
{
private $b;
private function getB()
{
if (null === $this->b)
{
$this->b = new B($this);
}
return $this->b;
}
}
class B
{
public function __construct(A $a)
{
}
}
也许你想使用像这样的东西:
class A
{
protected function __construct ()
{
}
}
class B extends A
{
public function __construct ()
{
$a = new A();
}
}
$b = new B();
使用get_called_class
来查找试图实例化对象的类:
class B
{
public function __construct ()
{
if(get_called_class() != 'A') {
//booboo
}
}
}
A
扩展 B
并且构造 B
而不是 A
时,这才能起作用。 - NikiC