0

我有一个单实例父类,它包含“本地全局属性”,每个子类都应该有权访问(也可以在更改时)

我可以想到两种方法来确保来自实例化父级的子级继承父级值:

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 是公开的,以使此示例更易于说明,但最终会受到保护)

4

2 回答 2

1

每个子类都应该有权访问(也可以在更改时)

这意味着您要使用静态变量,因为这正是它们的设计目的。

另一种选择是使用常量,但如果它们完全适合您的课程,那static就是要走的路

编辑:或者,如果您需要更复杂的东西,您可以使用@true 建议的模式。

于 2013-01-29T09:16:03.550 回答
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());

PS我没有测试过这段代码,只是为了展示一个想法

于 2013-01-29T09:21:51.930 回答