php 受保护的静态成员变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4280001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:31:05  来源:igfitidea点击:

Protected static member variables

phpstaticprotectedstatic-members

提问by netcoder

I've recently been working on some class files and I've noticed that the member variables had been set in a protected static mode like protected static $_someVar and accessed like static::$_someVar.

我最近一直在处理一些类文件,我注意到成员变量已被设置为受保护的静态模式,如 protected static $_someVar 并像 static::$_someVar 那样访问。

I understand the concept of visibility and that having something set as protected static will ensure the member variable can only be accessed in the super class or derived classes but can I access protected static variables only in static methods?

我理解可见性的概念,并且将某些设置为 protected static 将确保成员变量只能在超类或派生类中访问,但我只能在静态方法中访问 protected static 变量吗?

Thanks

谢谢

回答by netcoder

If I understand correctly, what you are referring to is called late-static bindings. If you have this:

如果我理解正确,您所指的称为后期静态绑定。如果你有这个:

class A {
   protected static $_foo = 'bar';

   protected static function test() {
      echo self::$_foo;
   }
}

class B extends A {
   protected static $_foo = 'baz';
}

B::test(); // outputs 'bar'

If you change the selfbit to:

如果您将self位更改为:

echo static::$_foo;

Then do:

然后做:

B::test(); // outputs 'baz'

Because selfrefers to the class where $_foowas defined (A), while staticreferences the class that called it at runtime (B).

因为self引用$_foo定义的类(A),而static引用在运行时调用它的类(B)。

And of course, yes you can access static protected members outside a static method (i.e.: object context), although visibility and scope still matters.

当然,是的,您可以访问静态方法之外的静态受保护成员(即:对象上下文),尽管可见性和范围仍然很重要。

回答by Chris Heald

Static variables exist on the class, rather than on instances of the class. You can access them from non-static methods, invoking them something like:

静态变量存在于类中,而不是类的实例中。您可以从非静态方法访问它们,调用它们如下:

self::$_someVar

The reason this works is that selfis a reference to the current class, rather than to the current instance (like $this).

这样做的原因是它self是对当前类的引用,而不是对当前实例(如$this)的引用。

By way of demonstration:

通过示范:

<?
class A {
  protected static $foo = "bar";

  public function bar() {
    echo self::$foo;
  }
}

class B extends A { }

$a = new A();
$a->bar();

$b = new B();
$b->bar();
?>

Output is barbar. However, if you try to access it directly:

输出是barbar。但是,如果您尝试直接访问它:

echo A::$foo;

Then PHP will properly complain at you for trying to access a protected member.

然后 PHP 会正确地向您抱怨试图访问受保护的成员。