note 57985 deleted from language.oop by danbrown
| From: | danbrown@php.net | Date: | Sat, 07 Nov 2009 19:03:17 +0000 |
| Subject: | note 57985 deleted from language.oop by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162558@lists.php.net to get a copy of this message | ||
Note Submitter: Karim Ahmed
----
This class method allows you to take a nice associative array of parameters into your class when the
number of parameters gets unmanagable and/or has lots of default-value parameters.
It is so useful I suggest putting on a general base class (I call mine Object) so all your
descendents can use it.
-----------------------------------------------------
Code:
-----------------------------------------------------
function setClassVars( &$parameter_array )
{
$class = get_class($this);
$class_vars = get_class_vars($class);
/*
* check that each of the passed parameters are valid before setting the
* appropriate class variable.
*/
foreach ( $parameter_array as $var => $value ){
if ( array_key_exists( $var, $class_vars ) ){
$this->$var = $value;
}
else{
$this->raiseError(
'setClassVars: class variable "' .
$var .
'" does not exist on class "' .
$class . '"'
);
}
}
}
-----------------------------------------------------
for example:
A complicated, messy, class method Before:
-----------------------------------------------------
render(
&$business_object,
$on_change=false,
$on_blur=false,
$options=false
$name
){
$this->business_object = $business_object;
$this->name = $name;
$this->on_blur = $on_blur;
$this->options = $options;
<code>
}
-----------------------------------------------------
A nice clean method After:
-----------------------------------------------------
render(
&$parameter_array
){
$this->setClassVars($parameter_array);
<code>
}
-----------------------------------------------------
Example call:
-----------------------------------------------------
$parameter_array =
array(
'business_object' => $business_object,
'name' => $field_name,
'on_change' => 'form.submit()',
'on_blur' => 'javascript:validate()',
$options =>
array(
'1' => 'None Selected',
'2' => 'Blue',
'3' => 'Red'
)
);
$my_object->render( &$parameters );
-----------------------------------------------------
Now isn't that easier to read AND maintain. Now you can change your API without the hassle of
amending every call to the method! You no longer have to worry about where the default params are or
even the order of your params.
I hope someone else who has been swearing at their code finds this useful ;-)