Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a class in PHP

Tags:

php

extend

class

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?

like image 214
Eskimo Avatar asked Jul 06 '26 00:07

Eskimo


2 Answers

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.

like image 149
lonesomeday Avatar answered Jul 08 '26 16:07

lonesomeday


Because you've used self in getInstance of class A, when you call getInstance in class B, I believe self is still refering to class A... if that makes any sense.

So basically, you're calling doStuff() on 2 instances of A.

like image 27
Jonnix Avatar answered Jul 08 '26 14:07

Jonnix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!