david
david

Reputation: 3360

How do you override self?

I want to build class that implement a lot of methods based on it's id, so I want to have one class parent that implement the methods! and when i want to use this class I will extend it and just override the id variable :

 class parent
    {
       $id = "parent";
       private __construct()
       { 
       }

       public static function create_instance()
       {
          $instance = new self();
          return $instance;
       }

       public static function print_id()
       {
          echo $this->id;
       }




    }

class child extend parent
{
   $id = "child";

}

$instance = child::create_instance();
$instance->print_id();

the result will be "parent", but I want the result to be child ? How to do that ?

EDIT : I also tried this and got parent instead of child:

class parent1 {
    private $id = "parent";
    public function __construct() {
    }
    public static function create_instance() {
        $instance = new static ();
        return $instance;
    }
    public function print_id() {
        echo $this->id;
    }
}
class child extends parent1 {
    private $id = "child";
}

$instance = child::create_instance ();
$instance->print_id ();

Upvotes: 2

Views: 577

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173542

The problem is that the visibility of $id is private whereas it should be protected because print_id() is only defined on the parent; as such it can only reach its own $id.

class parent1 {
    protected $id = "parent";
    // ...
}

class child extends parent1 {
    protected $id = "child";
}

The alternative is, of course, to override print_id() in the child class.

Upvotes: 2

Jakub Filipczyk
Jakub Filipczyk

Reputation: 1141

Currently when you call create_instance method on child class as a result instance of parent class is created not child class as you expect.

Use late static binding in parent class "create_instance" method:

public static function create_instance()
{
    $instance = new static();
    return $instance;
}

More details http://php.net/manual/en/language.oop5.late-static-bindings.php

Upvotes: 2

Related Questions