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

ˆᵛˆ*_*ˆᵛˆ 7 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.
    ?>
Run Code Online (Sandbox Code Playgroud)

这是可能吗?

Mag*_*eer 3

不是这样的。

如果您创建了像 return_some_array_filtered::go() 这样的静态方法,那么您可以使用 PHP5 的 autoload()工具来动态创建类和方法。创建后,呼叫将照常进行。您可能想在该类上实现callStatic() 。请注意,在 PHP 中从头开始动态创建类(不使用 include())并非易事。