使用PDO::FETCH_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;
}
我想知道,即使我们不这样做,这怎么可能有效 声明类属性? (见上文)
答案 0 :(得分:1)
在PHP中,如果在类定义中未声明属性时尝试在对象上分配属性,则将使用public
可见性声明属性并在运行时分配该属性。例如,如果我创建以下 empty 类:
class EmptyClass {}
然后实例化EmptyClass
的对象:
$c = new EmptyClass();
var_dump($c);
// class EmptyClass#2 (0) {
// }
在对象$c
上分配属性将隐式创建该公共属性:
$c->implicitProperty = "I have a value";
var_dump($c);
// class EmptyClass#2 (1) {
// public $implicitProperty =>
// string(14) "I have a value"
// }
从PDOStatement::fetch()
调用实例化对象时会发生同样的事情。
对于此PHP对象行为有用的用例,请参阅: