Home » Php » oop – Does extending a parent class in PHP require the file with the class being included?

oop – Does extending a parent class in PHP require the file with the class being included?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Should I include/require_once the parent class that I am extending in PHP?

for example I have a class called Shapes

class Shapes {

}

And then I created a subclass called

require_once('shapes.php');

class Circle extends Shapes {

}

Should I require the parent class when I am extending? or should just use extends the subclass to itss parent class even though they are in the same folder?

How to&Answers:

You need to do something in order to let PHP see your base class definition before it can process the child class, otherwise a fatal error will occur.

This something can be either a manual require_once of the base class file, or autoloading (there are other options for autoloading, but spl_autoload_register is the one you should use).

Which approach to use depends on the scope: when coding a small test project setting up autoloading is probably overkill. But as the code base gets larger and larger, autoloading becomes more attractive because:

  • it can hide complex source file resolution logic (e.g. if you have a configurable directory for the base classes; there are more advanced scenarios as well)
  • it can be configured incrementally: you can use multiple autoloaders that run as a chain, and each independent module of the application can register its independent autoloader that coexists peacefully with all the others

Answer:

Yes, you have to include it if that class is not declared in the same file.

Also there was a feature called Autoloading Classes with which you can create a function like this one:

function __autoload($class){
    require_once('classes/' . $class . '.php');
}

And it will automatically include classes which are not found in the existing scope

Also you can read about this feature too: autoload_register

Answer:

You can also use composer to simplify the process.

Make composer.json like this

{
...
    "autoload": {
        "psr-4": {
            "": "src/"
        }
    },
...
}

Get composer from https://getcomposer.org/ and run composer install.
You should load composer’s autoload script once like

require_once __DIR__ . '/vendor/autoload.php';

If you have PHP less than 5.3.0 then replace __DIR__ with dirname(__FILE__).

And put your files to src folder. For example if you have the class Acme\Utils\FooBar then it should be in src/Acme/Utils/FooBar.php.