我使用方法
得到了一个涉及symfony2中几个对象的变量\Doctrine\Common\Util\Debug::dump($article);
我有
array(1) { [0]=> object(stdClass)#267 (19) { ["__CLASS__"]=> string(30) "obbex\AdsBundle\Entity\AdsList" ["id"]=> int(33) ["username"]=> string(7) "aviator" ["email"]=> string(17) "aviator@gmail.com" ["telephone"]=> string(4) "5161"
["displayPhone"]=> string(3) "non" ["title"]=> string(14) "aviator jacket" ["description"]=> string(14) "aviator jacket" ["country"]=> string(6) "France"
["region"]=> string(13) "Ile de France" ["department"]=> string(5) "Paris" ["address"]=> string(15) "15, rue Dantzig" ["city"]=> string(5) "Paris" ["zipCode"]=>
string(5) "75015" ["statusPro"]=> string(3) "oui" ["creationtime"]=> string(8) "DateTime" ["updatetime"]=> string(8) "DateTime" ["publication"]=> bool(true) ["photos"]=> string(8) "Array(1)" } }
带
\Doctrine\Common\Util\Debug::dump($article[0]);
我可以访问第一个数组插槽[0]
object(stdClass)#267 (19) { ["__CLASS__"]=> string(30) "obbex\AdsBundle\Entity\AdsList" ["id"]=> int(33) ["username"]=> string(7) "aviator" ["email"]=> string(17)
"aviator@gmail.com" ["telephone"]=> string(4) "5161" ["displayPhone"]=> string(3) "non" ["title"]=> string(14) "aviator jacket" ["description"]=> string(14) "aviator jacket" ["country"]=> string(6) "France" ["region"]=> string(13) "Ile de France"
["department"]=> string(5) "Paris" ["address"]=> string(15) "15, rue Dantzig" ["city"]=> string(5) "Paris" ["zipCode"]=> string(5) "75015" ["statusPro"]=> string(3) "oui" ["creationtime"]=> object(stdClass)#365 (3) { ["__CLASS__"]=> string(8) "DateTime" ["date"]=> string(25) "2014-06-06T21:54:00+02:00" ["timezone"]=> string(12) "Europe/Paris" }
["updatetime"]=> object(stdClass)#366 (3) { ["__CLASS__"]=> string(8) "DateTime" ["date"]=> string(25) "-001-11-30T00:00:00+00:09" ["timezone"]=> string(12) "Europe/Paris" } ["publication"]=> bool(true) ["photos"]=> array(1) { [0]=> string(29) "obbex\AdsBundle\Entity\Photos" } }
如何访问第一个对象(stdClass)'obbex \ AdsBundle \ Entity \ AdsList' 我试过了
\Doctrine\Common\Util\Debug::dump($article[0]->{'obbex\AdsBundle\Entity\AdsList'});
和
\Doctrine\Common\Util\Debug::dump($article[0]->'obbex\AdsBundle\Entity\AdsList');
没有成功。
答案 0 :(得分:1)
我认为您的问题在于如何(取消)序列化您的对象。我假设你想要一个obbex\AdsBundle\Entity\AdsList
- 对象而不是stdClass
- 对象。
你可以做的是,检查__CLASS__
,然后从构造函数中传递stdClass
- 对象的对象创建一个新对象来传递数据:
$rawData = (array) $article[0]; // Convert stdClass to array for easier handling
$className = $rawData['__CLASS__'];
// TODO Maybe check, that class name is valid
$object = new $className($rawData);
您的类只需要在构造函数中填充数组中的属性:
namespace obbex\AdsBundle\Entity;
class AdsList
{
protected $username;
protected $email;
...
public function __construct(array $data = array())
{
if (empty($data)) {
return;
}
// TODO Check only valid properties/values are used
$this->username = $data['username'];
...
// OR
foreach ($data as $name => $value) {
$this->{$name} = $value;
}
}
}
您可以通过确保检索实际对象而不是stdClass
来节省一些麻烦,例如确保serialize()
和deserialize(string $serialized)
已实施/使用。