我有一个对象是数据库查询的结果,看起来像这样(var_dump 输出):
object(stdClass)#17 (6) {
["id"]=>
string(1) "1"
["title"]=>
string(20) "Some Title"
["description"]=>
string(41) "Some really good stuff. Description here."
["slug"]=>
string(19) "some-slug-url"
["picture_url"]=>
NULL
["price"]=>
string(4) "5.99"
}
我只需要将所有属性值“转移”到具有相同属性名称的不同类。有没有简单的方法可以做到这一点?
最佳答案
看看 PHP 的 get_object_vars()
-function无需大量赋值语句即可达到预期效果:
foreach (get_object_vars($sourceObject) as $name => $value) {
$destinationObject->$name = $value;
}
您应该确保根据您的需要为此添加足够的错误检查。
关于php - "Transfer"对象属性到不同类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6070109/