1

Let's say we have a class stockFns and I do

$stockFns->{$functionOne}=create_function('$a,$b' , 'return $a+$b;');

This creates a property in $stockFns named whatever create_function returned.

Now I want to refer (invoke) to the created_function.

What would be a clean way to do it in a single instruction?. An example

$stockFns=new StockFns;
$functionOne='add';
$stockFns->{$functionOne}=create_function('$a,$b' , 'return $a+$b;');

//echo "***" . ($stockFns->add)(1,2);  // That doesn't work
$theFn=$stockFns->add;
echo $theFn(1,2);         // This works but reuires two instructions

Thanks!

tru7
  • 6,348
  • 5
  • 35
  • 59
  • Forgot to menction, the name of the function is also a variable but I guess it doesn't matter in this problem. – tru7 Jun 08 '11 at 11:30
  • 1
    Can you give some context as to why you need to do this rather than create a new class which extends `StockFns`? – drewm Jun 08 '11 at 11:32
  • 1
    possible duplicate of [Calling closure assigned to object property directly](http://stackoverflow.com/questions/4535330/calling-closure-assigned-to-object-property-directly) – Gordon Jun 08 '11 at 11:33
  • drewm: Was thinking on possibilites on somehow flexible way to translate strings – tru7 Jun 09 '11 at 07:34

2 Answers2

2

Either your way, or

echo call_user_func(array($stockFbs, 'add'), 1, 2);

The problem is, that PHP cannot distinguish real methods from properties with callables. If you call something with () it will not touch the properties at all and in maybe will call __call, if it exists. You can try something like

class StockFns {
  public function __call ($name, $args) {
    $fctn = $this->{$name};
    return call_user_func_array($fctn, $args);
  }
}

As a workaround, so __call() will redirect to your callback.

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • see the linked duplicate as to why this may cause an infinite loop. you have to check if $name is callable. – Gordon Jun 08 '11 at 11:36
  • thanks. now its almost the same answer as in the linked dup. *cough* close *cough* vote. – Gordon Jun 08 '11 at 11:38
  • @Gordon: Ah, now I see, what you mean. I have omitted the checks, if everything is valid, to make it better readable. I think everybody should be able to find (at least the hard way ;)) the pitfalls and validate hisself. – KingCrunch Jun 08 '11 at 11:50
1

have you tried call_user_func?

http://php.net/manual/en/function.call-user-func.php

echo call_user_func(array($stockFns, $functionOne), 1, 2);

if you're using PHP5.3 and up, you should really consider using anonymous function

http://my.php.net/manual/en/functions.anonymous.php

Jeffrey04
  • 6,138
  • 12
  • 45
  • 68
  • Yes but I was searching something "clean" as the method would be called many times around the code. thanks! – tru7 Jun 09 '11 at 07:31