Need help on simple PHP loop to run on class objects

Tuesday, November 3, 2015

I am looking for a way to make this foreach loop run on the UserData objects.



 <?php
echo '<pre>';
class UserData{
public $FName;
public $LName;
public $IP;
}
$user001 = new UserData();
$user002 = new UserData();
$user003 = new UserData();

$user001->FName = 'Erez';
$user001->LName = 'T';
$user001->IP = '192.168.0.1';


$user002->FName = 'Netali';
$user002->LName = 'Goz';
$user002->IP = '192.168.0.2';

$user003->FName = 'Charley';
$user003->LName = 'Abu Ben David';
$user003->IP = '192.168.0.3';


So upto here the class has the attributes picked up by the new objects above.



Now from this part below i'm using the get_object_vars to retrieve the UserData, but I have no idea how to run it dynamically, can you help me with this in the shortest code possible with the most basic code (a for loop would be great!)



$vars = get_object_vars('UserData');
print_r($vars);
echo '<hr>';

foreach ($vars as $OP =>$OPVal){
echo $OP .' is '.$OPVal.'<br>';
}

?>


You can disregard the print_r and echo's.



Thanks!

0 comments:

Post a Comment