For PHP file calls, we sometimes have to consider the use of include, include_once, require, require_once. This is not only true for beginners, but also for advanced projects. And there is still no consensus on which one is optimal to use. Each team and each project has its own coding standards and its own reasons for using them. As for the similarities and differences of the four functions, we will not go into details here.
Our team recommends using require_once. Why use require_once instead of require. Give a reason today.
The use of require will cause redeclare errors when multiple subclasses inherit the same parent class
Because require is not a method, but a statement block. Therefore, he executes the referenced file once. Therefore, if you reference two classes that inherit from the same parent class in one file, the above problems will occur. But require_once does not. It will first determine whether it has been referenced, and skip it if so.
Looking at the code, first write an abstract parent class:
[php]
AbstractClass.php
AbstractClass.php
Implement two more subclasses:
[php]
RequireClassA.php
//Use require instead of require_once
require 'AbstractClass.php';
class RequireClassA extends AbstractClass{
}
RequireClassA.php
//Use require instead of require_once
require 'AbstractClass.php';
class RequireClassA extends AbstractClass{
}
[php]
RequireClassB.php
//Use require instead of require_once
require 'AbstractClass.php';class RequireClassB extends AbstractClass{}
RequireClassB.php
//Use require instead of require_once
require 'AbstractClass.php';class RequireClassB extends AbstractClass{}
Implementation call:
[php]
test.php
require_once 'RequireClassB.php';
require_once 'RequireClassA.php';
$A = new RequireClassA();
$B = new RequireClassB();
test.php
require_once 'RequireClassB.php';
require_once 'RequireClassA.php';
$A = new RequireClassA();
$B = new RequireClassB();
Running test.php reports an error
[plain]
>php test.php
>PHP Fatal error: Cannot redeclare class AbstractClass in /home/john/workspace/php/require/AbstractClass.php on line 2
>php test.php
>PHP Fatal error: Cannot redeclare class AbstractClass in /home/john/workspace/php/require/AbstractClass.php on line 2