Protected static member variables

冷暖自知 提交于 2019-11-29 12:27:03

问题


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.

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?

Thanks


回答1:


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

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

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

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

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

If you change the self bit to:

echo static::$_foo;

Then do:

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

Because self refers to the class where $_foo was defined (A), while static references the class that called it at runtime (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.




回答2:


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 self is a reference to the current class, rather than to the current instance (like $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:

echo A::$foo;

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



来源:https://stackoverflow.com/questions/4280001/protected-static-member-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!