PHP 使用魔法函式 __call 實現類似過載的功能
阿新 • • 發佈:2018-11-08
這幾天為了面試複習了php的魔法函式看到 __call
使我有了一個想法也許能夠用使用這個函式實現方法過載
public function __call($name, $arguments)
這是_call的函式頭,有被呼叫的函式名稱跟引數,我的想法是根據名稱然後匹配引數型別來實現過載。
經過除錯我發現 :呼叫類部已有的方法不會去呼叫__call
function testFuc1(string $str)
{
echo $str.PHP_EOL;
}
function testFuc2(int $int)
{
echo $int.PHP_EOL;
}
定義兩個測試函式 php7 當然這只是為了測試方便設定的,你也可以修改到支援到你的php版本。
class Test
{
private $matchingArgs = [];
public function __call($name, $arguments)
{
$args = $this->matchingArgs[$name];
if (count($args) == 0) {
return;
}
$argsType = [];
foreach ($arguments as $arg) {
array_push($argsType, gettype($arg));
}
foreach ($args as $math) {
if ($math['argsType'] == $argsType) {
return call_user_func_array($math['func'], $arguments);
}
}
}
public function addMethod($name, $args , $func)
{
$this->matchingArgs[$name][] = [
'argsType' => $args,
'func' => $func
];
}
}
這就是最終的類了,必須得手動新增類,其實可以使用反射來做。但是偷懶沒用
$t = new Test();
$t->addMethod('fuck', ['string'], 'testFuc1');
$t->addMethod('fuck', ['integer'], 'testFuc2');
$t->fuck('123');
$t->fuck(456);
一下是後期有空的可能會實現的功能
- 自動新增
- 支援類函式
- 靜態方法