10

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.

2 Answers 2

15

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. (rewriting comment, the previous ones didn't make sense) Can you access a static property declared in Child class, used in Parent class (late static binding), from another class, naming the Parent class, like in Another doing Parent::Prop (this doesn't work, but is there a way, doing some kind of late-static-binding-polymorphism)?
This makes no sense.
9

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

2 Comments

I will upvote this when I have the rep. The other answer is cleaner because it avoids calling parents of parents when inheritance is a long chain.
Thank you for your examples. I learned about late static binding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.