【问题标题】:Are there best practices for working with static members in PHP?是否有在 PHP 中使用静态成员的最佳实践?
【发布时间】:2014-08-06 01:19:14
【问题描述】:

PHP 允许使用静态成员函数和变量,因为 5.3 包括后期静态绑定:

class StaticClass {
    public static $staticVar;

    ...
}

$o = new StaticClass();

目前,访问这些静态成员有多种选择:

$o->staticVar;  // as instance variable/ function
$o::staticVar;  // as class variable/ function

还有其他选项可用于从类内部访问成员:

self::$staticVar;   // explicitly showing static usage of variable/ function
static::$staticVar; // allowing late static binding

重构一些使用静态成员的现有类我问自己是否有在 PHP 中使用静态成员的最佳实践?

【问题讨论】:

  • 不要使用$o->staticVar; 访问静态属性,因为这几天会发出警告;在课堂外使用StaticClass::staticVar;

标签: php static


【解决方案1】:

嗯,很明显,他们都做不同的事情。

$o->staticVar

这是无效,因为您不能/不应该使用实例属性语法访问静态属性。

StaticClass::$staticVar

这非常明显地访问了一个非常特定的类上的特定静态变量。

$o::$staticVar

这将访问$o 是其实例的类上的静态变量。它主要用作前一种方法的简写,并且在所有方面都是等效的。显然,使用哪个类完全取决于 $o 是哪个类的实例。

self::$staticVar

这只能在类中使用,并且总是引用它所写入的类。如果类引用自身,最好在类中使用 this 而不是 StaticClass::$staticVar,因为你不'如果您稍后更改类名,则无需担心任何事情。例如:

class Foo {

    protected static $bar = 42;

    public function baz() {
        self::$bar;  // good
        Foo::$bar    // the same, but should be avoided because it repeats the class name
    }

}
static::$staticVar

这也只能在类内部使用,与上面的self 基本相同,但通过后期静态绑定解析,因此可能引用子类。

什么是“最佳实践”值得商榷。我会说你应该总是尽可能具体,但仅此而已。 $o::$staticVarstatic::$staticVar 都允许类在子类中变化,而 self::$staticVarStaticClass::$staticVar 不允许。在open/closed principle 之后,最好使用前一种更可变的方法来允许扩展。

静态和非静态属性也不应该是public,以免破坏封装。

另见How Not To Kill Your Testability Using Statics

【讨论】:

  • 至少这在 PHP 中是不允许的,尽管它应该在成员变量上调用静态方法:$this->interpreter::staticMethod()
【解决方案2】:

首先,不要使用$this->staticVar。我不确定这种情况何时发生变化(我相信是 PHP 5.4),但在最近的版本中,不再可能以这种方式检索静态变量。

至于使用后期静态绑定,不需要就不要使用。使用它的原因是如果您打算使用继承并希望更改派生类中静态变量的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-05
    • 2010-09-18
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多