Search code examples
phpclassextend

Extending a class in PHP


class A{
  private static $instance;

  public static function getInstance(){

    if(!(self::$instance instanceof self))
      self::$instance = new self();

    return self::$instance;
  }

  public function doStuff(){
    echo 'stuff';
  }


}

class B extends A{
  public function doStuff(){
    echo 'other stuff';
  }
}

A::getInstance()->doStuff(); // prints "stuff"

B::getInstance()->doStuff(); // prints "stuff" instead of 'other stuff';

What am I doing wrong?

Why doesn't class B run it's function?


Solution

  • Look at the code in getInstance:

     if(!(self::$instance instanceof self))
           self::$instance = new self();
    

    All those selfs point to A, not to the class that was called. PHP 5.3 introduces something called "late static binding", which allows you to point to the class that was called, not to the class where the code exists. You need to use the static keyword:

    class A{
      protected static $instance;  // converted to protected so B can inherit
    
      public static function getInstance(){
        if(!(static::$instance instanceof static))
          static::$instance = new static(); // use B::$instance to store an instance of B
    
        return static::$instance;
      }
    
      public function doStuff(){
        echo 'stuff';
      }
    }
    

    Unfortunately, this will fail if you don't have PHP 5.3 at least.