我的PHP类函数看起来像从数据库表中获取数据时:
class my {
public $a;
public function myFunc(){
$query = mysql_query("select name,loc,info from stores");
while ($row = mysql_fetch_array($query)) {
extract($row);
echo $this->a;
}
}
}
我希望它应该打印在创建类的对象并调用类方法时调用的那些行的结果:
$class = new my();
$class->a = '<h1>$name</h1>';
$class->a .= '<p>$loc</p>';
$class->myFunc();
但它没有给出正确的结果并打印为:
$name
$loc
$name
$loc
$name
$loc
...
我希望它应该打印这些变量的值,这些变量实际上是表的行,结果应该是这样的:
london store
london near the big mall, england
PK world wide store
F-5 street near the new G-T road london
...
怎么可能?
谢谢。
答案 0 :(得分:0)
'<h1>$name</h1>'
和'<p>$loc</p>'
只是普通strings。它们内部的变量引用不会被echo
评估。
您可以返回项目并将其渲染到函数之外:
class my {
public function myFunc(){
$query = mysql_query("select name,loc,info from stores");
$items = array();
while ($row = mysql_fetch_array($query)) {
$items[] = $row;
}
return $items;
}
}
$class = new my();
$items = $class->myFunc();
foreach ($items as $item) {
echo "<h1>{$item['name']}</h1><p>{$item['loc']}</p>";
}
如果你坚持在功能中进行渲染,你可以传递anonymous function:
class my {
public $renderer;
public function myFunc(){
$query = mysql_query("select name,loc,info from stores");
while ($row = mysql_fetch_array($query)) {
call_user_func($this->renderer, $row);
}
}
}
$class = new my();
$class->renderer = function ($row) {
extract($row);
echo "<h1>$name</h1><p>$loc</p>";
};
$class->myFunc();
我在代码中使用了双引号字符串。请参阅PHP docs了解其中的差异,或参阅What is the difference between single-quoted and double-quoted strings in PHP?