PHP: 有关CodeIgniter3中函数名不能与控制器名相同的问题php
在CodeIgniter3开发中遇到一个问题:html
控制器名与方法名同名时,报"404 Page Not Found"错误。框架
好比有个控制器“Controllers/Login.php”:ide
class Login extends CI_Controller{ function login(){ echo 'login'; } }
预期结果是: 可使用“index.php/login/login”访问此login()函数,输出"login"字符串函数
实际结果是: 页面报出"404 Page Not Found"错误codeigniter
查看CodeIgniter3框架代码,在CodeIgniter.php中有这样一段代码:ui
require_once(APPPATH.'controllers/'.$RTR->directory.$class.'.php'); if ( ! class_exists($class, FALSE) OR $method[0] === '_' OR method_exists('CI_Controller', $method)){ $e404 = TRUE; } elseif (method_exists($class, '_remap')){ $params = array($method, array_slice($URI->rsegments, 2)); $method = '_remap'; } elseif ( ! is_callable(array($class, $method))){ ////问题在这里: ////is_callable(array($class, $method)) 返回 false. ////$class的值为 'Login', $method的值为'login', 方法login()被当成了控制器Login的构造函数(PHP4风格) $e404 = TRUE; }
问题就出在函数 is_callable() 上面, 从PHP5.3起,构造函数调用is_callable()检查会返回不可被调用。.net
$class 的值为 'Login', $method的值为'login', 方法login()被当成了控制器Login的构造函数(PHP4风格)code
查看CodeIgniter2中的CodeIgniter.php代码,没有发现有使用is_callable函数,因此CodeIgniter2不会有这个问题。orm
好吧,看来目前CodeIgniter3不能再使用控制器和方法名相同的命名了。
PHP手册上有这样一个示例:
Example #2 is_callable() and constructors As of PHP 5.3.0 is_callable() reports constructors as not being callable. This affects PHP 5 style constructors (__construct) as well as PHP 4 stlye constructors (i.e. methods with the same name as the class). Formerly, both cases have been considered callable. <?php class Foo{ public function __construct() {} public function foo() {} } var_dump( is_callable(array('Foo', '__construct')), is_callable(array('Foo', 'foo')) ); 上边这段代码将会输出: The above example will output: bool(false) bool(false)
参考资料:
http://codeigniter.org.cn/user_guide/general/controllers.html
http://php.net/manual/en/function.is-callable.php
[完]