我是Code igniter/OOP的新手,但正在努力解决这个问题。
我正在尝试制作一个可以在代码中使用的助手;这就是它的样子:
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('blah@website.com', 'James');
$this->email->subject($subject);
$this->email->message($body);
$this->email->send();
}
}
然后,我将其包含在助手的自动加载部分中。
当我试图在我的控制器中访问它时,我得到了一个错误。
$obect['FirstName']='Carl';
$obect['LastName']='Blah';
email('new', 'test@website.com', 'test', $object);
这是我得到的错误:
Fatal error: Using $this when not in object context in C:'inetpub'wwwroot'attrition'application'helpers'email_helper.php on line 17
您将使用该变量而不是$this
所以,你的$this是这个找零的
$CI =& get_instance();
如何使用?通常你会像一样使用$this
$this->load->other();
// change to
$CI->load->other();
它应该是工作
不在对象上下文中时使用$this
这只是意味着您不能在对象(类)之外使用$This关键字,正如@Kryten指出的那样。
帮助程序通常只用于嵌入html中,例如格式化数据。
<p><?php echo formatHelper(escape($var)); ?></p>
你需要做的是读一点关于创建图书馆的知识。
将函数更改为以下代码:
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('blah@website.com', 'James');
$this->email->subject($subject);
$this->email->message($body);
$this->email->send();
}
}