在php中是否有像魔术方法__call()这样的函数用于全局范围?

时间:2011-07-21 01:57:24

标签: php

如果对类中的未定义方法进行调用,则魔术方法__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.
    ?>

这一切都可能吗?

1 个答案:

答案 0 :(得分:2)

不是这样的。

如果您创建了一个类似return_some_array_filtered :: go()的静态方法,那么您可以使用PHP5的autoload()工具来动态创建类和方法。创建后,呼叫按常规进行。您可能希望在该类上实现callStatic()。注意在PHP中从头开始动态创建一个类(没有include())是非常重要的。