一个函数,想在所有的控制其中能够调用,写在什么地方最合适?

WBOY
Release: 2016-06-06 20:14:21
Original
895 people have browsed it

在CodeIgniter框架中,我写了一个 showMessage 的函数,用来跳转页面,我想在所有的控制其中都可以调用这个函数,写在什么地方是最合适的?

回复内容:

在CodeIgniter框架中,我写了一个 showMessage 的函数,用来跳转页面,我想在所有的控制其中都可以调用这个函数,写在什么地方是最合适的?

写个BaseController,所有其他的控制器继承BaseController。或者写个common类,里面写个静态方法showMessage,在index.php里面实例化这个common类,然后所有的controller里面就可以调用这个类的静态方法~

可以写成一个类,然后放到application目录下的libraries下。
需要用到的时候使用$this->load->library('yourClass');加载进去,也可以在config中设置自动加载。
然后使用$this->yourClass->yourFuns();调用。

不管写在什么地方都何时,就看你是想在执行函数的时候自动调用还是,手动加载这个文件再调用函数了,取决于你是打算怎么做的。细数Java,C++,等等语言,你想要调用类里的方法,首先都是在头部import进来,然后再使用。

相比类,可以尝试 helpers 并挂载到 autoload

如果只是一个函数,写成 helper 比较好。

还是 写在 help 比较好,可能你以后还需要添加其他的 通用方法 这样方便管理

ci框架本身的全局函数是在 /system/core/Common.php 可以放在这里,
也可以像Ahonn那样写成类,在config里设置自动加载这个类。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!