Search code examples
phpoopspl-autoload-register

PHP Autoloading Extended Classes


Based on the response from this question I would expect my code to work but for some reason it is not. I have a simple class that extends a class from my library of classes.

_custom.php

$custom = new MyClass();
class MyClass extends MyAbstractClass{

  public function __construct(){
      parent::__construct();
  }

}

Unfortunately I get this fatal error:

Fatal error: Class 'MyClass' not found in ...

But if I remove the extends MyAbstractClass then the error goes away. It seems the issue is that when attempting to extend the class, it does not attempt to load MyAbstactClass which then causes MyClass to not be found at all.

Any thoughts or suggestions on this?


Solution

  • PHP is an interpreted language, meaning that what is known for PHP to define is the code that parsed before a statement.

    class MyClass extends MyAbstractClass{
    
      public function __construct(){
          parent::__construct(); #you are forcing a construct call, it is not required if the parent constructor has no args.
      }
    
    }
    
    $custom = new MyClass();
    

    With classes you can prevent this behavior by using an autoloader, when an object is called and is undefined, it will try to inject and parse the class by your given code.

    You can define the magic function __autoload() but the spl_autoload_register() is preferred as it is more dynamic and not a constant as the __autoload() function is.