code igniter load library from within library?

2019-05-13 03:00发布

问题:

Is it possible to load an library from within a library in code igniter?

If I do

$this->validator = $this->CI->load->library('validators/'.$params['validator']);

from within another library $this->validator is NULL.

Why would this be?

回答1:

Check out the CI_Loader class's signature for the library() method you refer to:

/**
 * Class Loader
 *
 * This function lets users load and instantiate classes.
 * It is designed to be called from a user's app controllers.
 *
 * @access  public
 * @param   string  the name of the class
 * @param   mixed   the optional parameters
 * @param   string  an optional object name
 * @return  void
 */
function library($library = '', $params = NULL, $object_name = NULL)
{

It returns void, so of course whatever you set the return value to will be null. I think you're confused about the purpose of that method. Its to load the library and attach it to the codeigniter super-object, so that you can reference it as:

$this->CI->[library name]

In your case, you'll just want to refer to the newly-loaded library (some specific validator library I'm guessing based on your code snippet) in the usual way:

$this->CI->[newly loaded super awesome validator library]