[英]Code Igniter Custom Helper
I am new to Code igniter / OOP but trying to figure this out. 我是Code点火器/ OOP的新手,但试图弄清楚这一点。
I am trying to make a helper that I can use in my code; 我试图提供一个可以在我的代码中使用的助手; this is what it looks like:
看起来是这样的:
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();
}
}
I then include it in the autoload for the helper section. 然后,将其包括在帮助程序部分的自动加载中。
When i try to access it within my controller, I get an error. 当我尝试在控制器中访问它时,出现错误。
$obect['FirstName']='Carl';
$obect['LastName']='Blah';
email('new', 'test@website.com', 'test', $object);
Here is the error that I am getting: 这是我得到的错误:
Fatal error: Using $this when not in object context in C:\inetpub\wwwroot\attrition\application\helpers\email_helper.php on line 17
you'll use that variable instead of $this 您将使用该变量而不是$ this
so, your $this is change by this 因此,您的$ this被此更改
$CI =& get_instance();
How to use? 如何使用? usualy you use $this like
通常你用$ this这样
$this->load->other();
// change to
$CI->load->other();
It should be work 应该工作
change your function to this code : 将您的函数更改为此代码:
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();
}
}
Using $this when not in object context
不在对象上下文中时使用$ this
This simply means you can not use the $this keyword outside of an object(class), as @Kryten pointed out. 正如@Kryten所指出的,这仅意味着您不能在对象(类)之外使用$ this关键字。
Helpers are generally only used for embedding in html, such as formatting data. 通常,辅助程序仅用于嵌入html,例如格式化数据。
<p><?php echo formatHelper(escape($var)); ?></p>
What you need to do is read up a little on creating a Library . 您需要做的是阅读有关创建库的内容 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.