PHP Base Class Implementation with Iterator
This is a class definition for a base class which can be extended.
Features
- Attributes are defined dynamically
- Iteration is implemented, to allow the use of foreach
- Attribute validation is included
- Uses array_fill_keys if it is available, otherwise gracefully degrades to use a foreach loop
- Allows attribute assignment with an associative array
Base Class Definition
require_once 'include/common.php';
class Base Implements Iterator
{
/** Location for overloaded data. */
protected $data = array();
public function __construct($attribute_names=null,$attribute_values=null)
{
if ($attribute_names!==null)
{
if (function_exists(array_fill_keys))
$this->data=array_fill_keys($attribute_names,'');
else
foreach ($attribute_names as $v)
$this->data[$v]='';
if ($attribute_values!==null)
foreach ($attribute_values as $k => $v)
$this->$k=$v;
}
else
if (get_class($this)!=='Base')
halt(FAIL_CLASS_HAS_NO_ATTRIBUTES,get_class($this).' class has no attributes');
}
public function __set($name,$value)
{
if (array_key_exists($name,$this->data))
$this->data[$name]=$value;
else
halt(FAIL_INVALID_ATTRIBUTE,get_class($this).' invalid attribute '.$name);
}
public function __get($name)
{
if (array_key_exists($name,$this->data))
return($this->data[$name]);
else
return null;
}
public function __isset($name)
{
return isset($this->data[$name]);
}
public function rewind()
{
return reset($this->data);
}
public function current()
{
return current($this->data);
}
public function key()
{
return key($this->data);
}
public function next()
{
return next($this->data);
}
public function valid()
{
return current($this->data)!==false;
}
public function __destruct()
{
}
}
Extension Class
class User extends Base
{
public function __construct($aArgs=null)
{
bsBase::__construct(array(
'userID','roleName','userName',
'firstName','middleName','lastName','loginName',
'password','email','contactPhone'),$aArgs);
}
function __destruct()
{
}
}
Object Instantiation
/* Create a new user, with the userID set to 1 */
$oUser=new User(array('userID'=>1));
$oUser->firstName='John';
foreach ($oUser as $k => $v)
echo $k.' -> '.$v.PHP_EOL;
This post courtesy of Lyrix, Inc. / Mobiso
Print article | This entry was posted by elvis on 09/20/10 at 03:25:33 pm . Follow any responses to this post through RSS 2.0. |