我有一个单实例父类,它包含“本地全局属性”,每个子类都应该有权访问(同样在更改时)
我可以想出两种方法来确保来自实例化父级的子级继承父级值:
1)使用静态变量
class p
{
public static $var = 0;
}
class c extends p
{
function foo()
{
echo parent::$var;
}
}
$p = new p;
$c = new c;
$c->foo(); //echoes 0
p::$var = 2;
$c->foo(); //echoes 2
2)使用传递的对象
class p
{
public $var = 0;
}
class c extends p
{
function update_var(p $p)
{
$this->var = $p->var;
}
function foo()
{
echo $this->var;
}
}
$p = new p;
$c = new c;
$c->foo(); //echoes 0
$p->var = 2;
$c->update_var($p);
$c->foo(); //echoes 2
在我看来,静态解决方案是迄今为止最优雅的解决方案,但可能存在一些缺点,我没有看到。您认为哪种解决方案是最好的,还是有更好的选择?
(另请注意,在此示例中,$ var是公开的,以使此示例更容易说明,但最终会受到保护)
答案 0 :(得分:1)
每个子类都应该有权访问(当它被更改时)
这意味着您要使用静态变量,因为这正是它们的设计目的。
另一个选择是使用常量,但如果它们适合你的班级,那么static
就是你要走的路
编辑:或者,如果您需要更复杂的东西,可以使用建议的@true模式。
答案 1 :(得分:1)
也许最好将不同的对象作为这些变量的存储,可以注入每个对象?
更新变量的想法似乎很疯狂。
如果您需要更少的代码,可以使用静态变量执行此操作,但我会做一些配置容器,将在每个类中注入(阅读依赖注入:http://en.wikipedia.org/wiki/Dependency_injection)
class Config
{
protected $vars;
public function __get($name)
{
if (isset($this->vars[$name])) {
return $this->$name;
}
}
public function __set($name, $value)
{
return $this->vars[$name] = $value;
}
public function toArray()
{
return $this->vars;
}
}
class Component
{
protected $config;
public function __construct(Config $config = null)
{
$this->config = $config;
}
public function getConfig()
{
return $this->config;
}
}
// Create config instance
$config = new Config();
// Store variable
$config->testVar = 'test value';
// Create component and inject config
$component = new Component($config);
// Save another one variable in config
$config->test2Var = 'test 2 value';
// Create one more component and inject config
$component2 = new Component($config);
// Create one more varible
$config->someMoreVar = 'another one variable';
// Check configs in different components, values will be same (because config object is not cloned, just link to this object is saved in Component's $config property):
var_dump($component->getConfig()->toArray());
var_dump($component2->getConfig()->toArray());
P.S。我没有测试过这段代码,只是为了表达一个想法