代码点火器使用$this时出现致命错误


Codeigniter fatal error using $this

使用Codeigniter 2.2.1

我正在尝试使用以下示例解析RSS提要:http://hasokeric.github.io/codeigniter-rssparser/

我已经下载了库并添加到我的库文件夹中。

然后我把这个代码添加到我的视图中:

function get_ars() 
{
    // Load RSS Parser
    $this->load->library('rssparser');
    // Get 6 items from arstechnica
    $rss = $this->rssparser->set_feed_url('http://feeds.arstechnica.com/arstechnica/index/')->set_cache_life(30)->getFeed(6);
    foreach ($rss as $item)
    {
        echo $item['title'];
        echo $item['description'];
    }
}

当我调用函数get_ars();时,我得到以下错误:

致命错误:在第8行的C:''wamp''www''xxxxx''application''views''pagetop_view.php中,当不在对象上下文中时使用$this

我看了一下这篇文章,但它并没有解决我的问题。

有人能告诉我我做错了什么吗

不要在视图中直接包含函数代码
创建一个辅助函数,然后在视图中使用它。例如,

1)helpers/xyz_helper.php

function get_ars() 
{
    $ci =& get_instance();
    // Load RSS Parser
    $ci->load->library('rssparser');
    // Get 6 items from arstechnica
    $rss = $ci->rssparser->set_feed_url('http://feeds.arstechnica.com/arstechnica/index/')->set_cache_life(30)->getFeed(6);
    foreach ($rss as $item)
    {
        echo $item['title'];
        echo $item['description'];
    }
}


2)在自动加载文件(config/autoload.php)中加载助手

$autoload['helper'] = array('xyz_helper');


3)现在您可以在视图中使用它

<?php 
$ars = get_ars(); 
foreach($ars as $a) {
?>
...
...
<?php } ?>


阅读文档:
助手
创建库

尝试这个

$CI =& get_instance();

并且在此之后使用$CI而不是$this。

CodeIgniter是一个MVC框架。这意味着uou不应该试图在您的视图中加载内容或编写函数。

但是,您可以在视图中调用函数。这些函数必须在助手中编写。

有关更多详细信息,请参阅:http://www.codeigniter.com/user_guide/general/helpers.html

编辑:关于辅助解决方案,请参阅Parag Tyagi的答案

此外,在您的情况下,您应该能够通过将vars从控制器传递到视图来实现所需的功能。

我假设您的视图加载在index()中,并且您的视图名为"myview"。

控制器:

public function index()
{
    // Load RSS Parser
    $ci->load->library('rssparser');
    $data["rss"] = $ci->rssparser->set_feed_url('http://feeds.arstechnica.com/arstechnica/index/')->set_cache_life(30)->getFeed(6);
   $this->load->view("myview", $data);
}

视图:

<?php
foreach ($rss as $item)
{
    echo $item['title'];
    echo $item['description'];
}
?>