gpt4 book ai didi

php - 调用不存在的方法时重定向到其他方法

转载 作者:可可西里 更新时间:2023-11-01 00:03:48 26 4
gpt4 key购买 nike

如果我调用 $object->showSomething()showSomething 方法不存在,我会得到一个 fata 错误。没关系。

但是我有一个带有参数的show() 方法。我可以告诉 PHP 在遇到 $object->showSomething() 时调用 show('Something'); 吗?

最佳答案

尝试这样的事情:

<?php
class Foo {

public function show($stuff, $extra = '') {
echo $stuff, $extra;
}

public function __call($method, $args) {
if (preg_match('/^show(.+)$/i', $method, $matches)) {
list(, $stuff) = $matches;
array_unshift($args, $stuff);
return call_user_func_array(array($this, 'show'), $args);
}
else {
trigger_error('Unknown function '.__CLASS__.':'.$method, E_USER_ERROR);
}
}
}

$test = new Foo;
$test->showStuff();
$test->showMoreStuff(' and me too');
$test->showEvenMoreStuff();
$test->thisDoesNothing();

输出:

StuffMoreStuff 我也是 EvenMoreStuff

关于php - 调用不存在的方法时重定向到其他方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6268613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com