Dinge sind nicht so einfach, da gibt es keine Möglichkeit für PHP irgendwie magisch erraten, was mit den Werten dieses Array zu tun. Objekte sind eine strukturierte Menge von Daten im Gegensatz zu einem Array. Sie benötigen also eine Beschreibung der Struktur und Regeln, wie Sie sie verwenden können.
Sie müssen einen Konstruktor in der Klassendefinition implementieren, dann können Sie ein neues Objekt basierend auf einem bestimmten Array erstellen. Werfen Sie einen Blick auf diese willkürliches Beispiel:
<?php
class A {
protected $title;
protected $data;
public function __construct ($data) {
$this->title = $data['title'];
$this->data = sprintf('this is foo: %s', $data['foo']);
}
public function __toString() {
return sprintf(
"I am an object titled '%s'\nI hold that foo value: %s\n",
$this->title,
$this->data
);
}
}
$data = [
'title' => 'hello world',
'foo' => 'foovalue',
'bar' => 'barvalue'
];
$object = new A($data);
echo $object;
var_dump($object);
Die offensichtliche Ausgabe lautet:
I am an object titled 'hello world'
I hold that foo value: this is foo: foovalue
/home/arkascha/test.php:25:
class A#1 (2) {
protected $title =>
string(11) "hello world"
protected $data =>
string(21) "this is foo: foovalue"
}
Nun, _did Sie it_ versuchen? – arkascha
@arkascha kein Gedanke, ich würde zuerst fragen –
Mögliche Duplikate von [Typ Casting für benutzerdefinierte Objekte] (http://StackOverflow.com/Questions/1147109/Type-casting-for-user-defined-objects) –