【问题标题】:PHP MYSQL OOP Print the values of table rows which is called from outside variable to be printPHP MYSQL OOP 打印从外部变量调用的表行的值以进行打印
【发布时间】:2016-06-25 00:47:55
【问题描述】:

我的 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
...

这怎么可能?

谢谢。

【问题讨论】:

标签: php mysql oop


【解决方案1】:

'&lt;h1&gt;$name&lt;/h1&gt;''&lt;p&gt;$loc&lt;/p&gt;' 只是一个普通的 stringsecho 不会评估其中的变量引用。

您可以返回项目并在函数之外渲染它们:

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?

【讨论】:

  • 第二个是我的问题的解决方案。 谢谢
猜你喜欢
  • 1970-01-01
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
相关资源
最近更新 更多