3
votes

How would I include two functions with the same name in a php file?

I have two files:

file1.php which includes

function getResidentCount() {}

function getResidentData() {}

file2.php also includes

function getResidentCount() {}

function getResidentData() {}

I need file3.php to include all of these functions since each one is used to calculate different resident counts and data.

Any idea how I can include both of these files in one file. I cannot change the original files (they are in production for a live app).

Thanks, Claudia

5
Which PHP version do you use? - GolezTrol
put them in a separate file and include that - user557846
A quick workaround could be using namespaces. - Artefact2
that would need the include files to be modified though? - Paul Dixon

5 Answers

4
votes

This is evil. I only offer it as an exercise.

include('file1.php');
//include('file2.php'); 
$php=file_get_contents("file2.php");
$php=str_replace('getResidentCount', 'file2GetResidentCount', $php);
$php=str_replace('getResidentData', 'file2GetResidentData', $php);
eval($php);

Now you can call the duplicated function with a different name!

Do not do this. It's just an idea :)

An alternative would be use the APD extension, which lets you rename functions. Include the first file, rename its functions with rename_function, then include the second file.

Really, you should probably take a deep breath, delay what you're doing, and refactor what you have. Learn from it and change your practices so that it can't happen again. Namespaces might help you, a more object oriented approach might also.

2
votes

It's not possible to include both files as is. Doing so would result in PHP Fatal error: Cannot redeclare ....

Paul Dixon has provided a work around if you can't otherwise clean up your code.

1
votes

If you only need to use one of the functions per run of the script then you can use conditional inclusion:

if (some_condition) {
    require_once 'file1.php';
} else {
    require_once 'file2.php';
}
0
votes

I ended up nesting my functions for the page where I needed both sets of these functions. Thanks to all for your help.

0
votes

Looking for a solution to a similar answer, I was surprised to see nobody mentioned the anonymous function.

file1.php

$myfunction=function($val){
    //do something with val
    );

file2.php

$myfunction=function($val){
    //do something with val
    );

file3.php

for($i=1;$i<3;++$i){
    include_once('file'.$i.'.php');
    $result[$i]=$myfunction($val);
    }

The only drawback in this solution is that $myfunction gets overwritten, so it's not re-usable.

But this could perhaps be solved (not tested) with clone:

$allfunctions=[];    
for($i=1;$i<3;++$i){
        include_once('file'.$i.'.php');
        $allfunctions[$i]=clone $myfunction();
        }