PHP:从扩展类的方法访问父的静态变量

Edd*_*die 7 php oop variables static class

仍然试图在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();
?>
Run Code Online (Sandbox Code Playgroud)

我认为这可以从其他语言的经验中发挥作用.

dec*_*eze 9

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

self::$base_url
Run Code Online (Sandbox Code Playgroud)

要么

static::$base_url  // for late static binding
Run Code Online (Sandbox Code Playgroud)


rai*_*7ow 5

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

class dostuff extends config {
   public static function get_url(){
      echo parent::$base_url;
    }
}
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,您可以使用self::$base_url和访问它static::$base_url- 因为您不在扩展类中重新声明此属性.你这样做了,会有一个区别:

  • self::$base_url 总是会引用行写的同一个类中的属性,
  • static::$base_url 到对象所属类的属性(所谓的'后期静态绑定').

考虑这个例子:

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
Run Code Online (Sandbox Code Playgroud)