我的情况是在不同的班级中有类似的功能,让他们称呼他们"执行"和"执行。"
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移动到newVersion并执行此操作:< / p>
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
是否有一种花哨的解决方法,或者我发现并重写了每次通话?
答案 0 :(得分:1)
只需删除第一个调用&#34; real&#34;的执行函数。一。函数不区分大小写,因此您不必有两个
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);
答案 1 :(得分:1)
它有点乱,我通常不推荐它,但你可以使用PHP的“神奇”__call
方法模拟区分大小写的方法。只要在给定的类中找不到方法,就会调用此方法。然后,您可以检查提供的方法名称,并运行适当的逻辑。
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;
}
}