我有两个类(数据库查询数据库)和新闻操纵文章。在index.php(可以是任何其他页面)上,我调用News类,它调用Database类。一切顺利,直到我必须在index.php上显示结果。多维数组回顾(OOP)
比方说,我将结果保存在新闻类中的$ news。 我该如何检索index.php中的数组(如返回$ this-> news或其他东西??)。以及如何显示?
有人可以帮忙。
我有两个类(数据库查询数据库)和新闻操纵文章。在index.php(可以是任何其他页面)上,我调用News类,它调用Database类。一切顺利,直到我必须在index.php上显示结果。多维数组回顾(OOP)
比方说,我将结果保存在新闻类中的$ news。 我该如何检索index.php中的数组(如返回$ this-> news或其他东西??)。以及如何显示?
有人可以帮忙。
On index.php (could be any other page) i call News class, which calls Database class.
你不“叫班”。你可以调用类的方法。
Let's say, i save result in $news in News class.
我想你的意思是你有一个场(也财产在PHP)的名字news
,如:
class News {
private $news;
/* ... */
}
How should i retrieve that array in index.php (like return $this->news or something else??)
你可以在News
一个返回添加的方法此阵列:
class News {
private $news;
function retrieveNews() {
/* query the DB and store the result in $this->news */
}
function getData() { return $this->news; }
}
或者您可以公开并通过$newsObject->news
直接访问它(不推荐)。
And how to display?
这取决于数据的结构以及如何显示它。
掌声:d我不能做任何事情与问题:d – 2010-08-28 23:37:21
感谢回复, 第一,坏账的术语对不起,我不是本地人英语发音,所以话不容易:) 我的问题实际上是如何显示该内容(返回的数据),就是你在回复中停止的地方。 假设数据库查询是:“select news_id,title,body,date where author_id ='aid'”; 我将结果保存在$ this-> news中,并返回到index.php 现在我尝试使用foreach循环和其他一些函数,但没有成功。我的一个尝试: ($ i = 0; $ i <10; $ i ++)foreach($ news [$ i] as $ a => $ b){ echo $ b; } } 显示器本身的结构是另一个问题。 – phpEnthusiast 2010-08-28 23:49:34
@php同样,这取决于数据的结构。做一个'var_dump($ news)'看看它。 – Artefacto 2010-08-28 23:54:46
class Database{ // database.php
function news($user_id){
$q="select all from news where author id='$id'";
$result=$db->query($q);
for($i=0; $i<$r->num_rows; $i++){
$arr[]=$result->fetch_array;
}
return $arr; }}
class News{ // news.php
function get_news($user_id){
$news=$db->news($user_id);
return $news;
}}
index.php // problem how to display
$post=new News;
$post->get_news($user_id);
for($i=0; $i<5; $i++){
foreach($post[$i] as $k=>$v){
echo $v; //get error: "Cannot use object of type News as array in ..."
}}
后一些代码,否则就很难有什么用处你 – 2010-08-28 23:33:35