简体   繁体   中英

Overloading function construct when extends class PHP

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM