how to create array of all members of a class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

how to create array of all members of a class

Post by yacahuma »

Hello


I need a function that returns a nice path representation of a class. For example

class a
{
var $a1;
var $a2;

function __construct()
{
$this->a1 = new suba();
$this->a2 = new subb();
}
}

class suba
{
var $b1;
var $b2;
}


$arr = magic_function ('a');//pass the name of the class

print_r($a)
/a
/a/a1
/a/a1/b1
/a/a1/b2
/a/a2/b1
/a/a2/b2

So basically create a different kind of print_r. one that returns an array of the path to all members of the class, no matters how many classes down the tree I have.

Thank you
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

Re: how to create array of all members of a class

Post by yacahuma »

may not be pretty but this works. in case anyone need something like this.. Maybe the reflection class do this already. I dont know. If anyone knows if there is a php function to do this, please let me know.

Code: Select all

 
function createtree($classname,&$final,&$stack=array())
{
    $final[] = '/' . implode('/' , $stack) . '/' . $classname;
     try
     {
     $d = new ReflectionClass($classname);
     $f = array_keys($d->getdefaultProperties());
      array_push($stack,$classname);
      foreach($f as $el)
           createtree($el,$final,$stack);
       array_pop($stack);
     }
     catch (Exception  $e)
     {
       
     }
}
 
$output = array();
createtree('ScheduleG',$output);
foreach($output as $el)
echo '<br>' . $el;
 
Post Reply