如何向 class 对象添加值,然后将它们放入数组中?

How do I add values to class objects then put them in an array?

我正在尝试将查询嵌入到 class 中的变量中。
像这样:

    class FooBar{
        public $bar;
    }


    $result = array();

    $db = mysqli_connect("127.0.0.1", "foo", "foo", "Farm");
    $sql = "SELECT * FROM `Lot`;";
    $result = mysqli_query($db, $sql);

    while($row = mysqli_fetch_assoc($result)){
        $foo = new FooBar;            
        $foo->$bar = $row["cow"];

        array_push($result, $foo);
    }

但是当我使用 print_r($result) 打印数组时,我只是将其作为输出:

Array( )

我希望看到存储在数组中的对象。

我哪里做错了?我应该做什么?

您正在重复使用 $result 变量。它是一个数组,但您可以将其作为 MySQLi 资源重用。

另外 $foo->$bar 应该是 $foo->bar.

class FooBar{
    public $bar;
}


$result = array();

$db = mysqli_connect("127.0.0.1", "foo", "foo", "Farm");
$sql = "SELECT * FROM `Lot`;";
$query_result = mysqli_query($db, $sql);

while($row = mysqli_fetch_assoc($query_result)){
    $foo = new FooBar;            
    $foo->bar = $row["cow"];

    array_push($result, $foo);
}

var_dump($result);