On Tue, 7 Sep 2004 09:37:44 -0400, Mathieu Dumoulin
<[EMAIL PROTECTED]> wrote:
> I'm trying to setup a function from user code inside a defined object or a
> class definition but it doesnt seem to work. Am i doing it right? Is there
> something i need to know... is it even possible?
> 
> I know create_function can be used to create a function and it returns the
> ident to run the function later on, lookup create_function on php.net and it
> seems possible. Now i wonder if you can actually assign this function inside
> a class. My final goal is to create a set of functions or objects that will
> be able to "implement" interfaces to object classes, which is something
> missing to the PHP language.
> 
> ------------------
> RESULT
> ------------------
> allo
> Fatal error: Call to undefined function: b() in
> /home/tech/web/testboard/implements.php on line 21
> 
> -------------------------
> CODE
> -------------------------
> <?php
> class cls_a {
>  function a(){
>   echo 'allo';
>  }
> }
> 
> class impl_a {
>  function get_impl_b(){
>   return array('', 'echo "Hello world";');
>  }
> }
> 
> $a = new cls_a();
> $b_code = impl_a::get_impl_b();
> $a->b = create_function($b_code[0], $b_code[1]);
> $a->a();
> $a->b();
> ?>

First of all, I must say that from PHP5, the php (zend) engine does
support interfaces and implementing interfaces. So, maybe that's what
you're looking for... Anyway, now let's go on to helping you out with
your question.

Your approach is impossible. I'm stuck with the same thing, trying to
get the function name from a constant.. but there is a very nice way
of dealing with this. If you're running php5, it plainly works.
Earlier versions will need the (experimental) overload
(http://nl2.php.net/manual/en/ref.overload.php) function..


<?php
class Obj {
  var $gen = Array();
  function registerFunction($name, $args, $imp) {
    $this->gen[$name] = create_function($args, $imp);
  }
  function __call($n, $args) {
    call_user_func_array(Array(&$this, $this->gen[$n]), $args);
  }
}
?>

after a registerFunction call, you can call your function as you'd
expect to call it. Everything I just wrote is untested, but I'm pretty
sure it'll work - safe for maybe some typo's.

have fun!

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to