Let’s imagine we have few PHP files:
test1.php
<?php
function test() { echo "Test 1"; }
test();
?>
test2.php
<?php
function test() { echo "Test 2"; }
test();
?>
Some of function and variable names could be equal in these files.
Also, we have main PHP script, which need to run all of these sub-scripts:
<?php
include("test1.php");
include("test2.php");
?>
The problem is – functionsvariables are previously declared.
Question: is there a way to run such number of PHP scripts from general PHP script ?
I’m not familiar with classes, but I feel solution is somewhere here.
Thanks.
2
Answers
Yeah, you can use classes to avoid function name collisions. You can define each function in a separate class in each file, and then you can create an instance of each class and call the function in your main script.
Here’s how you can modify your
test1.php
andtest2.php
files.test1.php
test2.php
And here’s how you can modify your main script:
In the above code,
Test1
andTest2
are classes defined intest1.php
andtest2.php
respectively. Each class has atest
method. In the main script, we create an instance of each class and call thetest
method. This way, even though the method names are the same, they are in different classes, so there’s no name collision.You could use namespaces to solve this problem. Modify your include files to add a namespace declaration (for example for
test1.php
):Then in your main PHP file:
Output: