First let me introduce the class I want to work on. I have a class called dynamicObject that overloads the default __get() and __set() PHP functions to create essentially a dynamic class. It allows coding like the following:
Code: Select all
$test = new dynamicObject();
$test->someVar = "some value";
echo $test->someVar; // Prints "some value"Basically I want the object to act as an array as well. I want it so that when the object is put through a loop it loops through all it's current variables and returns their appropriate values (by using the array). In example:
Code: Select all
$test = new dynamicObject();
$test->someVar1 = "some value1";
$test->someVar2 = "some value2";
foreach($test as $name => $value)
{
// For the first loop $name should be "someVar1";
// For the first loop $value should be "some value1";
}If I lost anyone just ask and I'll try to add more to the explanation but in summary I just need a way to be able to iterate via a foreach() loop through all the variables in my dynamicObject class which are held in one array. Thanks in advance.
Cheers,
Josh
P.S Here is the code to my dynamicObject class:
Code: Select all
<?php
/**
* A dynamic class representing any object
*
* This class uses dynamic coding to create
* a class that can fit around almost any
* object. By overloading default class
* functions a dynamic environment can
* be created.
*
* @author Joshua Gilman (AliasXNeo)
*
*/
class dynamicObject
{
/**
* Mixed array used for holding class attributes
*
* @var Mixed
*/
private $details = array();
/**
* Class constructor
*
*/
function __construct()
{
}
/**
* The default __get() class function
*
* This function overloads the default __get()
* function allowing the class to take on a
* dynamic form.
*
* @param String $var
* @return Mixed
*/
function __get($var)
{
if (isset($this->{$var}))
{
return $this->{$var};
} else if(isset($this->details[$var])) {
return $this->details[$var];
} else {
return NULL;
}
}
/**
* The default __set() class function
*
* This function overloads the default __set()
* function allowing the class to take on a
* dynamic form.
*
* @param String $var
* @param Mixed $value
*/
function __set($var, $value)
{
if (isset($this->{$var}))
{
$this->{$var} = $value;
} else {
$this->details[$var] = $value;
}
}
/**
* Returns the current list of class attributes
*
* @return Mixed
*/
public function getAttributes()
{
return $this->details;
}
/**
* Returns the number of class attributes
*
* @return Integer
*/
public function numAttributes()
{
return sizeof($this->details);
}
}
?>