Passing a PHP array to a user object?

I have an array that I am retrieving from another source. Then this array should be run in the custom class that I created.

The reason I cannot use stdObject is because my class has a custom __getas well as a few convenience methods.

I basically need something like this:

$obj = (MyClass) $array;

What is not possible, it causes a syntax error.

+3
source share
3 answers

Create a constructor that takes an array and creates an object from this array.

+8
source

Perhaps you could achieve this with MyClass::__set_state($array)

+4

Theres I used to, but rather hacked, you can pass the array to stdclass, then serialize it to a string, and then use the string manipulation to change the class name and then unserialize 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 good method, but I consider it the only hack.

+3
source

Source: https://habr.com/ru/post/1782042/


All Articles