skip to Main Content

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


  1. 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 and test2.php files.

    test1.php

    class Test1 {
        public function test() {
            echo "Test 1";
        }
    }
    

    test2.php

    class Test2 {
        public function test() {
            echo "Test 2";
        }
    }
    

    And here’s how you can modify your main script:

    include("test1.php");
    include("test2.php");
    
    $test1 = new Test1();
    $test1->test();
    
    $test2 = new Test2();
    $test2->test();
    

    In the above code, Test1 and Test2 are classes defined in test1.php and test2.php respectively. Each class has a test method. In the main script, we create an instance of each class and call the test method. This way, even though the method names are the same, they are in different classes, so there’s no name collision.

    Login or Signup to reply.
  2. You could use namespaces to solve this problem. Modify your include files to add a namespace declaration (for example for test1.php):

    <?php
    namespace test1;
    
    function test() { echo "Test 1n"; }
    ?>
    

    Then in your main PHP file:

    include("test1.php");
    include("test2.php");
    
    function test() { echo "Test 3n"; }
    
    // call the different test functions
    test1test();
    test2test();
    test();
    

    Output:

    Test 1
    Test 2
    Test 3
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search