码迷,mamicode.com
首页 > Web开发 > 详细

PHP|ThinPHP5杂技

时间:2017-09-13 11:13:37      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:false   example   row   eth   exists   php手册   instance   代码   invoke   

ThinkPHP5.1

thinkphp\library\think\route\dispatch\Module.php P108 用到 is_callable()方法

        if (is_callable([$instance, $action])) {
            // 执行操作方法
            $call = [$instance, $action];
            // 自动获取请求变量
            $vars = $this->app->config(‘app.url_param_type‘)
            ? $this->app[‘request‘]->route()
            : $this->app[‘request‘]->param();
        } elseif (is_callable([$instance, ‘_empty‘])) {
            // 空操作
            $call = [$instance, ‘_empty‘];
            $vars = [$actionName];
        } else {
            // 操作不存在
            throw new HttpException(404, ‘method not exists:‘ . get_class($instance) . ‘->‘ . $action . ‘()‘);
        }

        $this->app[‘hook‘]->listen(‘action_begin‘, $call);

        return Container::getInstance()->invokeMethod($call, $vars);
    }

但是当 $instance中有 __call 方法时,is_callable([$instance, $action]) 返回的总为true,需要注意,貌似Thinkphp5中反射导致的__call方法无效(个人临时理解)

colin 03-Oct-2010 08:30  //代码块来自PHP手册

 I havent seen anyone note this before, but is_callable will correctly determine the existence of methods made with __call. The method_exists function will not.

 Example:
<?php

class Test {

     public function testing($not = false) {
         $not = $not ? true‘ : ‘false;
         echo "testing - not: $not<br/>";
     }
     
     public function __call($name, $args) {
         if(preg_match(‘/^not([A-Z]\w+)$/‘, $name, $matches)) {
             $fn_name = strtolower($matches[1]);
             if(method_exists($this, $fn_name)) {
                 $args[] = true; // add NOT boolean to args
                 return call_user_func_array(array($this, $matches[1]), $args);
             }
         }
         die("No method with name: $name<br/>");
     }

 }

$t = new Test();
$t->testing();
$t->notTesting();

 echo "exists: ".method_exists($t, ‘notTesting‘).‘<br/>‘;
 echo "callable: ".is_callable(array($t, ‘notTesting‘));

?>

 Output:

 testing - not: false
 testing - not: true
 exists:
 callable: 1 

 

PHP|ThinPHP5杂技

标签:false   example   row   eth   exists   php手册   instance   代码   invoke   

原文地址:http://www.cnblogs.com/8000cabbage/p/7513836.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!