0

I would like to have the functionality to set a function in a class (function setFunction). Later I want to get the function (with getFunction), which I can call from outside (specifying parameters etc. ). Here is what I have tried:

class Test
{
    var $function;

    function setFunction($foo)
    {
        $this->function = $foo;
    }

    function getFunction()
    {
        return $this->function;
    }

    function foo1($a)
    {
        print "foo1: ".$a."\n"; 
    }

    function foo2($b)
    {
        print "foo2: ".$b."\n"; 
        }

}

$oClass = new Test();
$oClass->setFunction($oClass->foo1);
$oClass->getFunction()('test'); # <--- line 32

The expected output is

foo1: test

But I get an error instead:

PHP Parse error:  syntax error, unexpected '(' in tester.php on line 32

Any ideas how to solve this? Here are some constraints:

  • This has to work for arbitrary parameters for each function.
  • The function to be defined is always specified in the class itself (if that helps).
hakre
  • 193,403
  • 52
  • 435
  • 836
Alex
  • 41,580
  • 88
  • 260
  • 469
  • 3
    Are you really still working with PHP4 or did you just mess up your tags? Also, have a look at [callables in PHP](http://php.net/manual/en/language.types.callable.php). – Till Helge Apr 19 '13 at 07:43
  • Yes, PHP4 is a requirement. – Alex Apr 19 '13 at 08:35
  • @Alex: Even you need PHP 4 code, the question per-se is not specific to PHP 4 therefore I removed the tag. I hope this is okay with you and write this just in case you wonder. – hakre Apr 19 '13 at 09:18

2 Answers2

4

You have to use call_user_func:

$oClass = new Test();
$oClass->setFunction(array($oClass, 'foo1'));
call_user_func($oClass->getFunction(), 'test');

array($oClass, 'foo1') is a callable, which represents an invocation of method foo1 on class instance $oClass.

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
-1

function in php is not a object what so ever. you can not do in this way.

caoglish
  • 1,343
  • 3
  • 19
  • 29