PHP中有没有办法让一个类只允许被另一个类实例化?例如:
<?php
class Graph {
private $nodes;
public function __construct() {
$this->nodes = array();
}
public function add_node() {
$this->nodes[] = new Node();
}
}
class Node {
public function __construct() {
}
}
?>
在我的示例中,我想阻止直接调用new Node()
。仅应从 Graph
类访问 Node
。
谢谢。
最佳答案
不,你不能这么做。您可以使用“hack”,如果传递给 Node 构造函数的参数不是图形,则在 Node 构造函数中抛出异常
class Node {
public function __construct() {
if(func_get_num_args() < 1 && !(func_get_args(0)instanceof Graph)){
throw BadCallException('You can\'t call Node outside a Graph');
}
}
}
关于PHP定义一个类只允许被另一个类实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12127917/