|
Posted by Janwillem Borleffs on 10/10/38 11:17
maxlego wrote:
> I am trying to dynamically create a new member function to my class. I
> have come up with this piece of code. It almost looks as if it adds
> the member functions to the class. But when trying to call them,
> nothing happens. Is this possible at all?
>
Not the way you are trying to, but it is possible using the classkit
extension (http://www.php.net/classkit).
> I am trying to do this thing because all the mmeber functions would
> have similar functionality except names. Since there are no
> facilities like C preprocessor I thought that eval might help.
>
Sounds to me that a __call() method would meet your needs:
<?php
class X {
private $members = array();
function __construct() {
$this->members[] = 'foo';
$this->members[] = 'bar';
}
function lambda($x) {
print $x;
}
function __call($name, $arg) {
if (!in_array($name, $this->members)) {
throw new Exception("No such method: $name()");
} else {
call_user_func_array(array($this,'lambda'), $arg);
}
}
}
$a = new X();
$a->bar(11);
?>
JW
[Back to original message]
|