使用 PDO::FETCH_CLASS 将 table 字段绑定到对象属性

Using PDO::FETCH_CLASS to bind table fields to object properties

使用 PDO::FETCH_CLASS 用返回的列值填充 class 字段 作为获取数据库的结果,我写了这样的代码。

<?php

class Recipe
{

    public $recipe_name;     // works without declaring variable here
    public $chef_name;       // works without declaring variable here
    public $num_ingredients; // works without declaring variable here

    public function __toString()
    {
        // Format output
        return sprintf(
        '<span class="recipe-name">%s</span>
            was made by <span class="chef-name">%s</span>,
            and it contains %s ingredients. <br />',
        $this->recipe_name,
        $this->chef_name,
        $this->num_ingredients
        );
    }
}

    ...
    ...

    if ($stmt) {
    if ($result = $stmt->execute()) {

        // Bind table fields to class properties..
        $recipe = $stmt->fetchAll(PDO::FETCH_CLASS, "Recipe");
    } else {

        echo "Query failed with message: " . $stmt->errorInfo()[2];
    }

}
...
...

// Show the results! We're done!
foreach ($recipe as $r) {
    echo $r;
}

我想知道,即使我们不这样做,这怎么可能奏效 声明 class 属性? (见上文)

在 PHP 中,如果在 Class 定义中尚未声明 [​​=39=] 时尝试在对象上分配 属性,则 属性 将以 public 可见性声明并在运行时分配。例如,如果我创建以下 empty class:

class EmptyClass {}

然后实例化一个EmptyClass的对象:

$c = new EmptyClass();
var_dump($c);
// class EmptyClass#2 (0) {
// }

在对象 $c 上分配 属性 将隐式创建 public 属性:

$c->implicitProperty = "I have a value";
var_dump($c);

// class EmptyClass#2 (1) {
//   public $implicitProperty =>
//   string(14) "I have a value"
// }

当您从 PDOStatement::fetch() 调用中实例化对象时,也会发生同样的事情。

对于此 PHP 对象行为有价值的用例,另请参阅:

  • Why implicit property declaration in PHP