[英]Call function present inside php class?
<?php
class MxitRSS {
function MxitRSS($rsslink,$noofposts = 3)
{
//'http://news.google.com/news?ned=us&topic=h&output=rss'
if($rsslink != NULL)
{
$rss = new DOMDocument();
$rss->load($rsslink);
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
for($x=0;$x<$limit;$x++) {
$randomnum= rand(5, 20);
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$date = date('l F d, Y', strtotime($feed[$x]['date']));
echo '<strong>'.$title.'</strong><br />';
echo '<i>Posted on '.$date.'</i>';
echo '<br/><br/>'.$description.'<br/>';
echo '<br/><a href=index.php?page=article&id='.$randomnum.'><i>read more</i></a><br/>';
}
} else { }
}
}
?>
通話功能
<?php
include('rss.php');
$this -> MxitRSS('http://news.google.com/news?ned=us&topic=h&output=rss',3);
?>
我正在嘗試在另一頁上調用上述函數,但是它不起作用。 我是php新手。 這很好嗎?
使用類的正確方法是首先實例化它。 但由於在這種情況下,類名等於方法名,因此您的方法是構造方法,並且在實例化該類后便會運行。 (以防您的php低於5.3。不建議使用此用法,而__construct是命名構造函數的新方法)
$myClass = new MxitRSS('http://news.google.com/news?ned=us&topic=h&output=rss',3);
實際上,因為您的類與函數具有相同的名稱,所以該函數將充當構造函數,
因此Volkan Ulukuts答案將兩次調用該函數,一次不使用URL,一次使用。
我不想要你
下面應該做你想要的。
<?php
include('rss.php');
new MxitRSS('http://news.google.com/news?ned=us&topic=h&output=rss',3);
?>
有一點需要注意的有趣的事情是,如果將“ MxitRSS”函數的名稱更改為“ __construct”,它的工作原理將完全相同,但是會使IMO更加清晰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.