Eddie
Eddie

Reputation: 1536

PHP: access a parent's static variable from an extended class' method

Still trying to figure out oop in PHP5. The question is, how to access a parent's static variable from an extended class' method. Example 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 experience in other languages.

Upvotes: 10

Views: 8741

Answers (2)

raina77ow
raina77ow

Reputation: 106385

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

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

But in this case you can access it both with self::$base_url and static::$base_url - as you don't redeclare this property in the extending class. Have you done it so, there would have been a distinction:

  • self::$base_url would always refer to the property in the same class that line's written,
  • static::$base_url to the property of the class the object belongs to (so called 'late static binding').

Consider this 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

Upvotes: 9

deceze
deceze

Reputation: 522024

It's completely irrelevant that the property is declared in the parent, you access it the way you access any static property:

self::$base_url

or

static::$base_url  // for late static binding

Upvotes: 15

Related Questions