0

I would like to create some class instances from php associative arrays. I need to create the object without calling the constructor, and then set its properties.

I was able to find the doctrine/instantiator, which does the object creation.

Unfortunately it is not able to set the properties. How is it possible? How does Doctrine hydrator solve this?

I could create a ReflectionClass, get the reflectionProperty, call ->setAccessible(true), and then set the attribute. But for thousands of objects, this solution is too slow.

Iter Ator
  • 8,226
  • 20
  • 73
  • 164
  • I'm curious as to why you need to do this. You could simply extend the class with a public hydrator method if using the constructor is not an option (why?). If speed is a concern and objects are in the thousands, using a library rig for the job seems counter-intuitive. – Markus AO Dec 28 '20 at 19:12
  • Because I have to build a library, and I don't know the classes before – Iter Ator Dec 28 '20 at 19:34
  • may be this could help you : https://stackoverflow.com/questions/6944946/instantiate-an-object-without-calling-its-constructor-in-php if you create a serialized object from your array and then unserialize it – Shaolin Dec 28 '20 at 19:54
  • If you don't know the classes before, how will you know the properties to be set? – Markus AO Dec 29 '20 at 11:35
  • @MarkusAO From an associative array. – Iter Ator Dec 29 '20 at 21:13
  • I don't follow why one would want to hydrate unknown classes. A class typically has a particular purpose and a matching set of properties. Here you have (presumably) known variables that you want to hydrate into unknown classes as private properties. Further, how does doing that accomplish the building of a library? – Markus AO Dec 30 '20 at 19:42

0 Answers0