1

i have two class:

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

   private function init()
   {
      //dosomething
   }
}

class Myclass extends BaseClass
{
   public function __construct()
   {

   }
}

now when i create:

$myclass = new Myclass;

function init is not running, somebody can help me?

1 Answer 1

5

That is because you are overriding your constructor within your child class. Just leave it out when you are not processing any tasks that differ from your parents constructor or call your parents constructor like that

class Myclass extends BaseClass
{
   public function __construct()
   {
       parent::__construct(); // Call the parents constructor
       // Do some stuff that explicitly belongs to the child class
   }
}

Let's take a look on what the PHP docs say on it:

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

Further reading:

PHP Docs - Constructors and Destructors

Sign up to request clarification or add additional context in comments.

1 Comment

$myclass = new Myclass('Name', 'Age', 'Coder'); now, i want in function init of class BaseClass, i can get value of parameter ('Name','Age','coder'), can u help me?

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.