download20151010 2013-01-15 05:01
浏览 136
已采纳

声明为static的属性无法使用实例化的类对象访问?

According to the php documentation http://php.net/manual/en/language.oop5.constants.php

A property declared as static can not be accessed with an instantiated class object

But doesn't the following example show that you can access a static property from the object $foo?

class Foo{
    static $my_static = 'foo';
    function staticValue(){
        return self::$my_static;
    }        
}

$foo = new Foo();
echo $foo::$my_static;
  • 写回答

1条回答 默认 最新

  • douweilei2307 2013-01-15 05:08
    关注

    The trick here is that you are using the scope resolution operator :: which always references the class. It doesn't matter if you use $foo or $this or self.

    Self is a keyword in PHP that references the current level, but :: can be used on an object to gain reference to the class for that object. self:: is in the same family of keywords as parent::, think of self:: as wanting access to something at the current level of an object, and parent:: as wanting access to something below the current object.

    Therefore, to access something that is defined in the class. PHP created the :: operator. If you just need something from the class that is static, then you can use self inside the class or an object reference outside it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退