3

I have an array which I retrieve from some other source. This array then needs to be casted into a custom class I've created.

The reason I can't use stdObject, is because my class has a custom __get as well as a number of convinience methods.

I basically need something like this:

$obj = (MyClass) $array;

Which does not look possible, it causes a syntax error.

hakre
  • 193,403
  • 52
  • 435
  • 836
Kristina
  • 15,859
  • 29
  • 111
  • 181

3 Answers3

8

Make a constructor that takes an array and constructs the object out of that array.

Femaref
  • 60,705
  • 7
  • 138
  • 176
4

Maybe you could achieve it with MyClass::__set_state($array)

Peter Souter
  • 5,110
  • 1
  • 33
  • 62
  • @nwinkler: Sure it does. Check the docs: http://php.net/manual/en/language.oop5.magic.php#object.set-state – geon Dec 17 '14 at 14:46
3

Theres a way which I have used before but is more of an hack, you can cast the array to an stdclass then serialize it into a string, then using string manipulation change the class name and then un-serialize the object:

function ClassCaster($class, $object)
{
    return unserialize(preg_replace('/^O:\d+:"[^"]++"/', 'O:' . strlen($class) . ':"' . $class . '"', serialize($object)));
}

class SampleClass
{
    public function __wakeup(){ /*Generic wake up from serialization */}
}

$array = array(/* ... */);
$SampleClass = ClassCaster("SampleClass",(object)$array);

This is not a pretty method but i believe its the only hack about.

RobertPitt
  • 56,863
  • 21
  • 114
  • 161