我正在尝试构建一个自定义库,其中包含可以在整个站点上使用的函数。在/application/libraries中,我创建了一个新文件:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * @brief CommonFuncts
 * This class is used to provide common user functions to the whole application.
 *
 * @version 1.0
 * @date May 2012
 *
 *
 */
class CommonFuncts extends CI_Controller {

 protected $ci;

/**
 * function constructor
 */
function __construct()
{
    $this->ci =& get_instance();
}
 /**
* @brief checkCookie
*
* Checks for a previous cookie, and if exists:
* @li Loads user details to CI Session object.
* @li Redirects to the corresponding page.
*
*/
public function verificaCookie(){
    $this->ci->load->view('index');
}
 }
/* End of file CommonFuncts.php */
/* Location: ./application/libraries/CommonFuncts.php */

在控制器中:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

/**
 * Index Page for this controller.
 *
 * Maps to the following URL
 *      http://example.com/index.php/welcome
 *  - or -
 *      http://example.com/index.php/welcome/index
 *  - or -
 * Since this controller is set as the default controller in
 * config/routes.php, it's displayed at http://example.com/
 *
 * So any other public methods not prefixed with an underscore will
 * map to /index.php/welcome/<method_name>
 * @see http://codeigniter.com/user_guide/general/urls.html
 */
public function index()
{
    $this->load->library('commonFuncts');
    $this->commonFuncts->verificaCookie();
}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

我收到以下错误消息:
A PHP Error was encountered

Severity: Notice

Message: Undefined property: Welcome::$commonFuncts

Filename: controllers/welcome.php

Line Number: 23

Fatal error: Call to a member function verificaCookie() on a non-object in
/var/www/vhosts/unikodf.com/httpdocs/application/controllers/welcome.php on line 23

我尝试过很多方法,包括在库中扩展CustomFuncts和使用welcome.php$this->ci->load->view,但仍然得到了相同的消息。

最佳答案

如果库扩展CI_Controller。这意味着您实际上是在扩展控制器的功能。而是像这样声明库:

class CommonFuncts { }

您不需要从CI_Controller继承,因为您编写的库不是控制器,而且库也不是mvc模型的一部分。它是一个类,扩展了框架的特性,修复了一个常见问题,或者具有许多控制器使用的功能。
要访问它的方法,请使用:
$this->load->library('CommonFuncts');
$this->commonfuncts->verificaCookie();

如果要简化调用库的名称,请使用:
// The second argument is the optional configuration passed to the library
// The third argument is the name with which you would like to access it
$this->load->library('CommonFuncts', '', 'common');
$this->common->verificaCookie(); //  /\ = configuration
//     /\/\/\ = name

10-02 04:32