Home  >  Article  >  Backend Development  >  ci框架如何通过$this->load->library向自定义的类中的构造函数传参?

ci框架如何通过$this->load->library向自定义的类中的构造函数传参?

WBOY
WBOYOriginal
2016-06-06 20:41:141680browse

<code>class blog_lib{

  var $CI;
  var $posts_path;
  var $file_ext='.md';

  var $_all_posts;
  var $_all_tags;
  var $_all_pockets;
    public function __construct($pathselect)
    {

    if (!isset($this->CI))
    {
        $this->CI =& get_instance();
    }
    $this->posts_path = FCPATH.$pathselect;

    }
</code>

控制器:

<code>public function index()
{  

$this->load->library('blog_lib');
$data['config'] = $this->blog_config;
$this->load->library('twig_lib');    
$data['all_tags'] = $this->blog_lib->get_posts_tags();    
$data['posts'] = $this->blog_lib->get_posts();
$this->twig_lib->render("index.html",$data); 
}
</code>

如上我该如何向构造函数传参?

回复内容:

<code>class blog_lib{

  var $CI;
  var $posts_path;
  var $file_ext='.md';

  var $_all_posts;
  var $_all_tags;
  var $_all_pockets;
    public function __construct($pathselect)
    {

    if (!isset($this->CI))
    {
        $this->CI =& get_instance();
    }
    $this->posts_path = FCPATH.$pathselect;

    }
</code>

控制器:

<code>public function index()
{  

$this->load->library('blog_lib');
$data['config'] = $this->blog_config;
$this->load->library('twig_lib');    
$data['all_tags'] = $this->blog_lib->get_posts_tags();    
$data['posts'] = $this->blog_lib->get_posts();
$this->twig_lib->render("index.html",$data); 
}
</code>

如上我该如何向构造函数传参?

CI是可以往类的构造函数传递参数的,但是构造函数的接受参数时必须是一个数组:

<code>class blog_lib{
    ...
    public function __construct($param){
        ...
        $this->posts_path = FCPATH.$param['pathselect'];
    }
    ...
}
</code>

Controller 里面:

<code>$this->load->library('blog_lib',array('pathselect'=> 'xx'));
</code>

如果觉得这种方式不好可以用另一个方式,就是在ci的自定义的class做一个虚拟的空类,然后在空类之后再定义一个真实的类,通过config/autoload.php 自动载入这个类,就可以new了,那个时候怎样传递都可以。
application/library/blog.php :

<code>//虚拟类
class blog{}

// 真实类
class blog_lib {
    ....
}
</code>

config/autoload.php

<code>$autoload['libraries'] = array('blog');
</code>

Controller 里面:

<code>$oblog = new blog_lib($value);
</code>
Statement:
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