受保护的静态成员变量 [英] Protected static member variables

查看:95
本文介绍了受保护的静态成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在处理一些类文件,并且我注意到成员变量已在受保护的静态模式下设置,例如受保护的静态$ _someVar,并以static :: $$ someVar的方式访问.

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?

谢谢

推荐答案

如果我理解正确,那么您指的是

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'

如果将self位更改为:

echo static::$_foo;

然后做:

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

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

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.

这篇关于受保护的静态成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆