开发者

PHP Two functions with same name

开发者 https://www.devze.com 2023-04-13 09:01 出处:网络
How would I include two functions with the same name in a php file? I have two files: file1.php which includes

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.

A开发者_开发问答ny 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


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.


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.


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';
}


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


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();
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消