Code-Igniter:load&在图书馆发送电子邮件

时间:2012-02-16 13:13:07

标签: codeigniter

我在CodeIgniter中有一个名为“someclass”的库。

class someclass extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->library('email');
        $this->load->database();

       // $this->load-> library('database');

    }
    function email($naar=0,$onderwerp=0,$bericht=0){
        if ($naar > 0 && $naar<10) {

            $to = "tester@test.com"
            //this is the part where it goes wrong            

            $CI =& get_instance();
            $this->load->library('email');               
            //some one said that i needed ti assign the library's
            $this->_assign_libraries();

            $this->email->from('tester@test.com', 'test');
            $this->email->to($to);
            $this->email->subject($onderwerp);
            $this->email->message("Test

                bericht :
                ".$bericht);

            $this->email->send();
            // echo $this->email-> print_debugger();
        }
    }
}

我收到以下错误:

A PHP Error was encountered

Severity: Notice

Message: Undefined property: someclass::$email

Filename: libraries/someclass.php

Line Number: 139

2 个答案:

答案 0 :(得分:7)

我的愿景可以有两种情况。

  1. 首先,您可以使用帮助。创建一个.php文件(例如:general_helper.php),可以在您使用它的地方自动加载或加载。如果来自config / autoload.php,则使用“常规”名称进行自动加载。
  2. 在这里,您可以创建一个名为sendEmail

    的方法
    function sendEmail($naar=0,$onderwerp=0,$bericht=0)
    {
        $CI =& get_instance();
    
            $CI->load->library('email');               
            //or autoload it from /application/config/autoload.php
    
            $CI->email->from('tester@test.com', 'test');
            $CI->email->to($to);
            $CI->email->subject($onderwerp);
            $CI->email->message("Test
    
                bericht :
                ".$bericht);
    
            $CI->email->send();
    
    }
    

    将自定义库加载到控制器中,并使用sendEmail(....)

    调用ID
    1. 您可以扩展原生电子邮件库类在该类中创建名为sendEmail的方法,例如:

      类MY_Email扩展CI_Email {     公共函数_ construct()     {     父:: _construct();     }     公共函数sendEmail().....等 }

    2. 从您的控制器加载本机库类,使用$this->load->library('email')并通过致电$this->email->sendEmail(...)发送您的电子邮件

答案 1 :(得分:0)

你做错了!你想写自己的图书馆吗?或者您是否正在尝试为页面编写控制器?

如果您正在尝试编写控制器,则无需运行get_instance()功能。只需扩展CI_Controller类,加载相应的库,在本例中为email,并根据文档使用它。此外,控制器将放在controllers文件夹中。

但是如果您正在尝试编写库,则无法从CI_Controller类扩展。您还需要使用get_instance()函数获取CodeIgniter的实例并将其存储在变量中。之后,只需使用该对象加载email库并发送电子邮件。

另外,我认为你不能从该类调用带下划线前缀的方法。我在说$this->_assign_libraries()。在CodeIgniter中,以下划线为前缀的方法是private函数。因此,您无法从自己的类中访问它。 (当然,除非它是一个protected函数并且你扩展了类。)