在PHP中遍历类对象?

时间:2019-06-11 16:38:54

标签: php

既然我将其转换为类,我可以弄清楚如何从数据库中遍历一个表。

旧代码

<?php
$sql = "WHERE * FROM Somewere";
$result = $pdo->query($sql);
$products = $result->fetchAll(PDO::FETCH_ASSOC);
?>

<?php foreach ($products as $product) ?>

新代码

<?php
class Posts extends Database
{
    public function postsToPost()
    {

        $stmt = $this->connect()->prepare("WHERE * FROM Somewere");
        $stmt->execute();

        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    }

}
?>

<?php foreach ($products as $product) ?>

我现在需要在类内部循环然后在页面中输出吗? 我很困惑。 谢谢

1 个答案:

答案 0 :(得分:0)

您可以返回结果:

class Posts extends Database
{
    public function postsToPost()
    {

        $stmt = $this->connect()->prepare("WHERE * FROM Somewere");
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);

    }

}

然后实例化Posts,如下所示:

$posts = new Posts();
$products = $posts->postsToPost();
foreach ($products as $product);