Re: how to dynamically create member functions



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



.



Relevant Pages

  • how to dynamically create member functions
    ... I am trying to dynamically create a new member function to my class. ... Since there are no facilities like ... C preprocessor I thought that eval might help. ... maxlego. ...
    (alt.php)
  • Re: Code explain...
    ... also declared as static in a member function meaing that it's lifetime ... Node appears to be a data member of type array of array of NodeData, ... So Nodeis an object of type NodeData. ... NodeData's declaration is missing from your code. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: A challenge: Routing algorithm in C++
    ... Then a method (member function in C++) which compares 2 units should ... Then parse the array and put each unit into its own Unit object. ... If K is needed loop over the sorted vector and set K for each Unit ...
    (comp.programming)
  • Strange CObArray access violation
    ... I've added a new member function which ... throws an access violation exception every time I try to access the ... I have initialized the array within the Class initialization list, ...
    (microsoft.public.vc.mfc)
  • Re: assignment operator=
    ... > language special edition" and found nothing related. ... does whatever to an array, you can wrap such an array ... inside a class, and create an operator=member function, ...
    (comp.lang.cpp)