Does parent class extend in PHP file with class included?

Should I include / require _once the parent class that I am distributing in PHP?

for example, I have a Shapes class

class Shapes { } 

And then I created a subclass called

 require_once('shapes.php'); class Circle extends Shapes { } 

Should I require a parent class when I expand? or should just use extends the subclass to its parent class, even if they are in the same folder?

+7
source share
3 answers

You need to do something so that PHP sees the definition of the base class before it can process the child class, otherwise a fatal error will occur.

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

Which approach to use depends on the volume: when coding a small test project that sets up autoload, perhaps too much. But as the code base becomes more and more, autoload becomes more attractive because:

  • it can hide the complex logic of resolving the source file (for example, if you have a custom directory for base classes, there are more complex scripts)
  • it can be configured gradually: you can use several autoloaders that run as a chain, and each independent application module can register its own independent autoloader, which coexists peacefully with everyone else.
+13
source

Yes, you should include it if this class is not declared in the same file.

Also, the function Autoload classes has appeared , with which you can create such a function:

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

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

Also you can read about this function also: autoload_register

+2
source

You can also use the composer to simplify the process.

Make composer.json as follows

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

Get the composer from https://getcomposer.org/ and run composer install . You should load the autoload script composition once, for example

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

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

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

+1
source

All Articles