2014-10-10 84 views
0

我是代码点火器/面向对象的新手,但试图弄清楚这一点。代码点火器自定义帮助程序

我试图做一个帮手,我可以在我的代码中使用;这看起来是这样的:

if (! function_exists('email')) 
{ 
    function email($type, $to, $subject, $object) 
    { 
     switch($type){ 

      case 'new': 

       $body = "Hello ". $object['FirstName'] . ' ' . $object['LastName'] . "," 
        . "<p/><p/>Thank you."; 
       break; 
     } 

     // Send it 
     $this->load->library('email'); 
     $this->email->to($to); 
     $this->email->from('[email protected]', 'James'); 
     $this->email->subject($subject); 
     $this->email->message($body); 
     $this->email->send(); 

    } 
} 

然后我将它包含在辅助部分的自动加载中。

当我尝试在我的控制器中访问它时,出现错误。

$obect['FirstName']='Carl'; 
$obect['LastName']='Blah'; 
email('new', '[email protected]', 'test', $object); 

这里是我得到的错误:

Fatal error: Using $this when not in object context in C:\inetpub\wwwroot\attrition\application\helpers\email_helper.php on line 17 
+0

尝试$对象 - >名字,并确保使用“J” – dandavis 2014-10-10 22:26:49

+1

基本上,它归结为:如果你在一个实例化的类的方法中执行代码,'$ this'关键字才有意义 - 否则,没有'$ this'来引用。我承认这个答案可能不足以帮助你解决你的问题 - 一个完整的解释需要更长的时间。你将需要对面向对象编程做更多的研究。 – Kryten 2014-10-10 22:27:59

回答

0

使用$此在不对象上下文

这只是表示您不能像@Kryten指出的那样在对象(类), 之外使用$ this关键字。

助手通常只用于嵌入到html中,如格式化数据。

<p><?php echo formatHelper(escape($var)); ?></p> 

你需要做的是读了一点关于创建Library

0

改变你的函数的代码:

if (! function_exists('email')) 
{ 
    function email($type, $to, $subject, $object) 
    { 
     switch($type){ 

      case 'new': 

       $body = "Hello ". $object['FirstName'] . ' ' . $object['LastName'] . "," 
        . "<p/><p/>Thank you."; 
       break; 
     } 

     // Send it 
     $this = &get_instance(); // here you need to get instance of codeigniter for use it 
     $this->load->library('email'); 
     $this->email->to($to); 
     $this->email->from('[email protected]', 'James'); 
     $this->email->subject($subject); 
     $this->email->message($body); 
     $this->email->send(); 

    } 
} 
1

你会使用这个变量而不是$这

这样,你的$这是改变这个

$CI =& get_instance(); 

如何使用? usualy你拼写“对象”时,使用$此类似

$this->load->other(); 
// change to 
$CI->load->other(); 

它应该是工作