Single File Inclusion in PHP
Let's say we have a file pow.php that
stores a set of functions:
<?php
function square($num) {
return $num ** 2;
}
function cube() {
return $num ** 3;
}
?>
Let's say we use the functions from the file pow.php
in the file sum.php:
<?php
require 'pow.php';
function squareSum($arr) {
$res = 0;
foreach ($arr as $elem) {
$res += square($elem);
}
return $res;
}
function cubeSum($arr) {
$res = 0;
foreach ($arr as $elem) {
$res += cube($elem);
}
return $res;
}
?>
Let's say in the main file we include both files with functions:
<?php
require 'pow.php';
require 'sum.php';
echo square(3) + squareSum([1, 2, 3]);
?>
However, we face a problem. The file
pow.php will be included twice in the file index.php:
once directly and once through the file
sum.php.
This will cause a problem because we will have two sets of functions with the same names.
To solve the problem, all files should be
included using the require_once
operator - it will include the file only once,
ignoring repeated inclusions:
<?php
require_once 'pow.php';
require_once 'sum.php';
echo square(3) + squareSum([1, 2, 3]);
?>
Create several files with useful sets of functions. Connect these files to each other and to your main file.