0

Is it possible to dynamically discover the properties of a PHP object? I have an object I want to strip and return it as a fully filled stdClass object, therefore I need to get rid of some sublevel - internal - objecttypes used in the input.

My guess is I need it to be recursive, since properties of objects in the source-object can contain objects, and so on.

Any suggestions, I'm kinda stuck? I've tried fiddling with the reflection-class, get_object_vars and casting the object to an array. All without any success to be honest..

Ben Fransen
  • 10,884
  • 18
  • 76
  • 129

2 Answers2

1

You can walk through an object's (public) properties using foreach:

foreach ($object as $property => $value)
 ... // do stuff

if you encounter another object in there (if (is_object($value))), you would have to repeat the same thing. Ideally, this would happen in a recursive function.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • The property I'm after to dive in is private, unfortunately. This question is an addition to my other question http://stackoverflow.com/questions/8297741/php-analyzing-handling-and-converting-some-object-to-a-stdclass any suggestion? – Ben Fransen Nov 29 '11 at 10:09
  • @Ben you need to add that to your question, it's a crucial piece of information – Pekka Nov 29 '11 at 10:29
  • @Ben related: [Call private methods and private properties from outside a class in PHP](http://stackoverflow.com/q/2738663) – Pekka Nov 29 '11 at 10:30
  • I've solved my problem: http://stackoverflow.com/questions/8297741/php-analyzing-handling-and-converting-some-object-to-a-stdclass/8312008#8312008 thanks for your help! +1, since both answers work and I can only accept one I'll reward Amado. – Ben Fransen Nov 29 '11 at 14:03
1

tested and this seems to work:

<?php

class myobj {private $privatevar = 'private'; public $hello = 'hellooo';}

$obj = (object)array('one' => 1, 'two' => (object)array('sub' => (object)(array('three' => 3, 'obj' => new myobj))));

var_dump($obj);

echo "\n", json_encode($obj), "\n";

$recursive_public_vars = json_decode(json_encode($obj));

var_dump($recursive_public_vars);
Amado Martinez
  • 429
  • 2
  • 8
  • 1
    Although it is not the solution to my problem (my solution is here http://stackoverflow.com/questions/8297741/php-analyzing-handling-and-converting-some-object-to-a-stdclass/8312008#8312008), this does what I asked in the question. Therefore +1 and accepted. Thanks! – Ben Fransen Nov 29 '11 at 14:04