当前位置:Gxlcms > PHP教程 > ci框架如何通过$this->load->library向自定义的类中的构造函数传参?

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

时间:2021-07-01 10:21:17 帮助过:35人阅读

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;

    }

控制器:

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); 
}

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

回复内容:

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;

    }

控制器:

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); 
}

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

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

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

Controller 里面:

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

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

//虚拟类
class blog{}

// 真实类
class blog_lib {
    ....
}

config/autoload.php

$autoload['libraries'] = array('blog');

Controller 里面:

$oblog = new blog_lib($value);

人气教程排行