PHP: access to parent static variable from extended class method

Still trying to calculate oop in PHP5. The question is how to access the parent static variable from the extended class method. An example is below.

<?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();
?>

I thought this would work from the experience of other languages.

+4
source share
2 answers

It doesn't matter at all that the property is declared in the parent, you get access to it the way you get access to the static property:

self::$base_url

or

static::$base_url  // for late static binding
+6
source

Yes, it is possible, but it should actually be written like this:

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

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
+4

All Articles