gpt4 book ai didi

php - 在 php 中是否有类似魔法方法 __call() 的全局作用域的函数?

转载 作者:可可西里 更新时间:2023-11-01 12:59:24 24 4
gpt4 key购买 nike

如果对类中未定义的方法进行调用,魔术方法 __call 可以拦截该调用,因此我可以按我认为合适的方式处理这种情况: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods

php 中是否提供了任何机制,使我可以在全局范围内对函数执行相同的操作。 最好用代码说明这一点:

    <?php
function return_some_array(){
$a = array();
//Do stuff to array
return array();
}

// Now i call the function like so:
$give_me_array = return_some_array();

// But sometimes I want the array to not contain zeroes, nulls etc.
// so I call:
$give_me_array_filtered = return_some_array_filtered();

// But i haven't defined return_some_array_filtered() anywhere.
// Instead I would like to do something like so:
function __magic_call($function_name_passed_automatically){
preg_match('/(.*)_filtered$/', $function_name_passed_automatically, $matches);
$function_name_that_i_defined_earlier_called_return_some_array = $matches[1];
if($matches){
$result = call_user_func($function_name_that_i_defined_earlier_called_return_some_array);
$filtered = array_filter($result);
return $filtered;
}
}

//So now, I could call return_some_other_array_filtered() and it would work provided I had defined return_some_other_array().
//Or even Donkey_filtered() would work, provided I had defined Donkey() somewhere.
?>

这有可能吗?

最佳答案

不是这样的。

如果你创建了一个像 return_some_array_filtered::go() 这样的静态方法,那么你可以使用 PHP5 的 autoload()动态创建类和方法的工具。创建后,调用照常进行。您可能想要实现 callStatic()在那个类(class)。当心在 PHP 中从头开始动态创建一个类(没有 include())是非常重要的。

关于php - 在 php 中是否有类似魔法方法 __call() 的全局作用域的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6770545/

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