开发者

Creating a variable_function as member of a class

开发者 https://www.devze.com 2023-03-11 16:23 出处:网络
Let\'s say we have a class stockFns and I do $stockFns->{$fu开发者_StackOverflow社区nctionOne}=create_function(\'$a,$b\' , \'return $a+$b;\');

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

$stockFns->{$fu开发者_StackOverflow社区nctionOne}=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!


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消