| //========================================================================== |
| //=== THE POWER HORSE! |
| //========================================================================== |
| |
| abstract class dynamic_params { |
| |
| //the only method needed |
| final public function call($method, array $set_params) { |
| |
| //get what paramters the method expects |
| $reflected_method = new ReflectionMethod(get_class($this), $method); |
| |
| //get ready to build up the list of params |
| $params = array(); |
| |
| //now loop through the properties of the method that is about to be called |
| foreach ($reflected_method->getParameters() as $i => $param) { |
| |
| //see if it exists |
| if (isset($set_params[$param->getName()])) { |
| $params[] = "'{$set_params[$param->getName()]}'"; |
| } else { |
| if ($param->isOptional()) { |
| $params[] = 'null'; |
| } else { |
| trigger_error("The parameter \"{$param->getName()}\" is required!", E_USER_ERROR); |
| } |
| } |
| |
| } |
| |
| //build up the params ready to be evaled in the method |
| $params = implode(',',$params); |
| |
| //execute the constructed method |
| eval("\$this->{$method}({$params});"); |
| |
| } |
| |
| } |
| |
| //========================================================================== |
| //=== EXAMPLE |
| //========================================================================== |
| |
| class typewriter extends dynamic_params { |
| |
| public function write($string, $color = 'black', $size = '12') { |
| print "<span style='font-size:{$size}px;color:{$color};'>{$string}</span>"; |
| } |
| |
| } |
| |
| |
| $machine = new typewriter(); |
| |
| //calls the write() method with string and size params set, but NOT the middle color param ;-) |
| $machine->call( |
| //the method to call in the class |
| 'write', |
| //the paramters that you want to pass to the method (all left out paramters are assigned with null |
| array( |
| 'string' => 'hello world', |
| 'size' => '16' |
| ) |
| ); |
| |
| //calls the write() method with just a size set, resulting in a fatal error because string is required |
| $machine->call( |
| //the method to call in the class |
| 'write', |
| //the paramters that you want to pass to the method (all left out paramters are assigned with null |
| array( |
| 'size' => '16' |
| ) |
| ); |