forethought
forethought

Reputation: 3253

how to make parent method to be called using $this->methodName in PHP?

I have two classes. One is parent and another is child. Both have a same name method. The problem is that parent method does not get called using $this->methodName.

Parent class

class Parent
{

    public function __construct()
    {
        $this->init();
    }

    // this function never get executed and why?
    public function init()
    {

       //do something

    }
}

The Child class

class Child extends Parent
{

   public function __construct()
   {
      parent::__construct();
      $this->init();
   }

   public function init()
   {
   // do something different
   }
}

How to call the parent method without using parent::init?

Upvotes: 0

Views: 106

Answers (3)

GertG
GertG

Reputation: 979

You can use self to refer to the current class. As opposed to $this, which refers to the current object at runtime.

class ParentClass
{

    public function __construct()
    {
        self::init();
    }

    public function init()
    {   
        echo 'parent<br/>';
    }
}

Upvotes: 3

Maytyn
Maytyn

Reputation: 122

<?php
    public function __construct(){
        parent::__construct();
        self::init();
    }
?>

Additionaly in Parent class use also self to avoid executing parent init and child init.

Upvotes: 0

Andr&#233; Ferraz
Andr&#233; Ferraz

Reputation: 1521

The thing is parent:: is there for a reason and one of those reason is to deal with the "problem" (which is not a problem) you have.

Obviously if you have a child class with a function called e.g myfunction() and a parent class with a function called myfunction(), if you use $this->myfunction() in the child it will obvious call the child's myfunction() function because $this is a reference to the current object.

There is no harm in using parent, it is there for a reason.

Upvotes: 0

Related Questions