Search code examples
phpinheritanceconstructorspl-autoload-register

Why is the parent's constructor being called


I have the simplest bit of code :

Interface

interface iCrudRepository{
    public function Create($id);
    public function Read($id);
    public function Update($id);
    public function Delete($id);
}

Parent

class Repository
{
   function __construct()
   {
     echo "SHOULD NOT BE CALLED AUTOMATICALLY";
   }
}

Class

require_once(__DIR__.'/../injection/bootstrap.php');

class Admin extends Repository implements iCrudRepository
{
  function Create($id)
  {
  }

  function Read($id)
  {
  }

  function Update($id)
  {
  }

  function Delete($id)
  {
  }
}

$admin = new Admin();
$admin->Create("Something");

The bootstrap class autoloads my classes via the spl_autoload_register function. Since in the Admin class I don't call the parent constructor, it shouldn't execute what is in the parent's constructor right?

The Output

SHOULD NOT BE CALLED AUTOMATICALLY

Probably missing something obvious here but can't quite figure out why it is called.


Solution

  • Docs state:

    Parent constructors are not called implicitly if the child class defines a constructor.

    So you have to do this in order to prevent what you are seeing:

    class Admin extends Repository implements iCrudRepository
    {
        public function __construct()
        {
    
        }
      function Create($id)
      {
      }
    
      function Read($id)
      {
      }
    
      function Update($id)
      {
      }
    
      function Delete($id)
      {
      }
    }