![](/img/trans.png)
[英]Codeigniter __construct being called multiple times in controller
[英]Why are two controller methods being called in CodeIgniter?
我是否不应该将Index
用作CodeIgniter中控制器类的名称? 我有一个Index控制器,并且看到它的方法被多次调用。 更具体地说,无论我是否正在访问应该路由到那里的路径,我总是看到其index
方法首先被调用。
在application / controllers / index.php中
class Index extends CI_Controller
{
public function index()
{
echo "index";
}
public function blah()
{
echo "blah";
}
}
当我访问index/blah
,我看到indexblah
打印出来。 当我访问index/index
,看到indexindex
。 如果我将控制器重命名为其他名称(例如Foo),则没有问题。 那是显而易见的解决方法,但是谁能告诉我为什么会这样吗? 我是否应该将此错误报告给CodeIgniter?
(注意:我没有在configs/routes.php
中configs/routes.php
路由;我的index.php
在CodeIgniter树之外)
谁能告诉我为什么会这样?
实例化控制器的get时,将调用构造函数的index
。
比较构造函数和析构函数文档 :
为了向后兼容,如果PHP 5找不到给定类的__construct()函数,它将按该类的名称搜索旧式的构造函数。 [由我突出显示]
在您的情况下,Controller没有任何__construct()
函数,但是具有与class: index
相同名称的函数。 当Codeigniter解析并加载然后实例化Index
控制器时,就会调用它。
您可以通过将构造函数添加到Controller中来解决此问题:
class Index extends CI_Controller
{
public function __construct() {}
public function index()
{
echo "index";
}
public function blah()
{
echo "blah";
}
}
更改之后,不会再发生。
我是否应该将此错误报告给CodeIgniter?
不,实际上并不需要将其报告为错误,这是语言的工作方式,并且由于Codeigniter支持PHP 4,它必须保持向后兼容,并且需要提供PHP 4构造函数。 (注意:Codeigniter项目文档,他们需要服务器支持PHP 5.1.6或更高版本,但是实际代码具有内置的PHP 4兼容性,我在这里指的是代码库,而不是文档。)
为了进一步阐明问题所在,在PHP4中,构造函数是一个与类同名的函数。
例
class MyClass
{
public function MyClass()
{
// as a constructor, this function is called every
// time a new "MyClass" object is created
}
}
现在为PHP5版本(从2.0.x版本开始,现在有哪个codeigniter作为系统要求)
class MyClass
{
public function __construct()
{
// as a constructor, this function is called every
// time a new "MyClass" object is created
}
}
因此,要回答解决该问题的问题...
我是否不应该将Index用作CodeIgniter中控制器类的名称?
我相信最好不要选择Index
作为控制器名称,因为index()
函数在codeigniter中具有保留用途。 这可能会导致问题,具体取决于您的PHP配置。
这是使用Codeigniter3的另一种解决方案
require_once 'Base.php';
class Index extends Base
{
public function __construct()
{
parent::index();
$classname=$this->router->fetch_class();
$actioname=$this->router->fetch_method();
if($actioname=='index' || $actioname == '')
{
$this->viewall();
}
}
}
并且viewall()具有以下内容
$this->siteinfo['site_title'].=' | Welcome';
$this->load->view('templates/header', $this->siteinfo);
$this->load->view('templates/menu', $this->siteinfo);
$this->load->view('index/viewall', $data);
$this->load->view('templates/footer', $this->siteinfo);
Base控制器负责整个应用程序的所有库和辅助程序加载,这就是为什么默认类中需要它的原因
基本上从我对CodeIgniter的简短了解来看,将默认操作作为索引是错误的。 我通过打印$ this-> router-> fetch_method();的结果发现了这一点。 在我的索引类的Construct()中。 CodeIgniter的默认操作是index,您只能在application / config / routes.php中设置默认控制器,而不能设置默认操作。
因此,我的建议是,不要将index()用作默认操作,尤其是当您使用index作为默认控制器时
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.