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

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

WBOY
Release: 2016-06-06 20:41:14
Original
1712 people have browsed it

<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>
Copy after login
Copy after login

控制器:

<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>
Copy after login
Copy after login

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

回复内容:

<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>
Copy after login
Copy after login

控制器:

<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>
Copy after login
Copy after login

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

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

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

Controller 里面:

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

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

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

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

config/autoload.php

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

Controller 里面:

<code>$oblog = new blog_lib($value);
</code>
Copy after login
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