【问题标题】:PHP: access a parent's static variable from an extended class' methodPHP:从扩展类的方法访问父级的静态变量
【发布时间】:2014-01-07 21:48:06
【问题描述】:

仍在尝试找出 PHP5 中的 oop。问题是,如何从扩展类的方法中访问父类的静态变量。下面的例子。

<?php
error_reporting(E_ALL);
class config {
    public static $base_url = 'http://example.moo';
}
class dostuff extends config {
   public static function get_url(){
      echo $base_url;
    }
}
 dostuff::get_url();
?>

我认为这可以根据使用其他语言的经验来实现。

【问题讨论】:

    标签: php class oop variables static


    【解决方案1】:

    在父级中声明属性完全无关紧要,您可以像访问任何静态属性一样访问它:

    self::$base_url
    

    static::$base_url  // for late static binding
    

    【讨论】:

    • 谢谢。 (重写注释,前面的没有意义)你能不能访问一个在 Child 类中声明的静态属性,在 Parent 类中使用(后期静态绑定),从另一个类,命名 Parent 类,就像在Another 做@ 987654324@(这不起作用,但有办法,做某种后期静态绑定多态)?
    • 这毫无意义。
    【解决方案2】:

    是的,有可能,但实际上应该这样写:

    class dostuff extends config {
       public static function get_url(){
          echo parent::$base_url;
        }
    }
    

    但在这种情况下,您可以使用self::$base_urlstatic::$base_url 访问它——因为您没有在扩展类中重新声明此属性。你这样做了,会有区别的:

    • self::$base_url 将始终引用该行所写的同一类中的属性,
    • static::$base_url 指向对象所属类的属性(所谓的“后期静态绑定”)。

    考虑一下example

    class config {
      public static $base_url = 'http://config.example.com';
      public function get_self_url() {
        return self::$base_url;
      }
      public function get_static_url() {
        return static::$base_url;
      }
    }
    class dostuff extends config {
      public static $base_url = 'http://dostuff.example.com';
    }
    
    $a = new config();
    echo $a->get_self_url(), PHP_EOL;
    echo $a->get_static_url(), PHP_EOL; // both config.example.com
    
    $b = new dostuff();
    echo $b->get_self_url(), PHP_EOL;   // config.example.com
    echo $b->get_static_url(), PHP_EOL; // dostuff.example.com
    

    【讨论】:

    • 当我有代表时,我会对此表示赞同。另一个答案更简洁,因为它避免在继承是长链时调用父母的父母。
    • 感谢您的示例。我了解了后期静态绑定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 2015-07-22
    • 2012-06-29
    相关资源
    最近更新 更多