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?
This principle will affect the way many classes and objects relate to one another. For example, when extending a class, the subclass inherits all of the public and protected methods, properties and constants from the parent class. Unless a class overrides those methods, they will retain their original functionality.
The extends keyword is used to derive a class from another class. This is called inheritance. A derived class has all of the public and protected properties of the class that it is derived from.
Classes, case classes, objects, and traits can all extend no more than one class but can extend multiple traits at the same time.
A child class can override any public parent's method that is not defined with the final modifier. Also, classes with final modifier cannot be extended.
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:
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With