PHP: 处理函数不区分大小写

PHP: Dealing with function case-insensitivity

我有一种情况,在不同的 class 中有类似的功能,我们称它们为 "Execute" 和 "execute."

class oldVersion {
    public function Execute($x){
        echo 'This does the same thing as newVersion->execute(1)';
        echo 'but the class contains a lot of garbage that PHP7 doesn\'t like.';
        echo 'and the app dies if it\'s included';
    }
}

class newVersion {
    public function execute($x, $y = 0, $z = 0){
        if($y == 1){
            echo 'do thing one';
        } else {
            echo 'do thing zero';
        }
        return 'bar';
    }
}
$obj1 = new oldVersion();
$obj1->Execute('foo');

$obj2 = new newVersion();
$obj2->execute('bar', 1);

class oldVersion 有很多问题,在 PHP7 下根本无法运行,所以我真正希望能够做的是将 Execute 移入新版本并执行此操作:

class oldVersion_deprecated {
    // no longer included so PHP7 doesn't break
}

class newVersion {
    public function Execute($x){
        return $this->execute($x, 1);
    }
    public function execute($x, $y = 0, $z = 0){
        if($y == 1){
            echo 'do thing one';
        } else {
            echo 'do thing two';
        }
        return 'bar';
    }
}

$obj1 = new newVersion();
$obj1->Execute('foo');

$obj2 = new newVersion();
$obj2->execute('bar', 1);

但我自然而然地得到

FATAL ERROR: cannot redefine execute

是否有一个奇特的解决方法,或者我是否一直在查找和重写每个调用?

只需删除第一个调用 "real" 函数的执行函数。函数不区分大小写,因此您不必有两个

class newVersion {
 public function execute($x, $y = 0, $z = 0){
    if($y == 1){
        echo 'do thing one';
    } else {
        echo 'do thing two';
    }
    return 'bar';
   }
 }
 /* All the same */
 echo newv->Execute('foo');
 echo newv->ExEcUTe('foo');  
 echo newv->execute('bar', 1);

有点乱,我通常不推荐它,但你可以用PHP的"magic" __call方法模拟区分大小写的方法。只要在给定 class 中找不到方法,就会调用此方法。然后您可以检查提供的方法名称,以及 运行 任何合适的逻辑。

class Foo
{
    public function __call($name, $args)
    {
        switch ($name) {
            case 'Execute':
                return $this->oldExecute(...$args);
            case 'execute':
                return $this->newExecute(...$args);
        }
    }

    private function oldExecute($x)
    {
        echo 'Running old function with arg: ', $x, PHP_EOL;
    }

    private function newExecute($x, $y, $z)
    {
        echo 'Running new function with args: ', implode(',', [$x, $y, $z]), PHP_EOL;
    }
}

https://eval.in/926262