douza19870617 2016-05-21 08:31
浏览 27
已采纳

数组到字符串转换 - 变量函数名称调用

I need to call some functions inside a class; based on variables, something like this:

$x->$y();

But, I found a strange behavior, consider the following sample code:

$arr = array(

    "some_index" => "func_name"
);


$str = "func_name";

class some_class {

    public function func_name() {

        echo "It works in class!";
    }
}

$some_obj = new some_class();

$some_obj->$arr['some_index']();
$some_obj->$str();

Now the line

$some_obj->$arr['some_index']();

gives the errors:

Array to string conversion in ...
Undefined property: some_class::$Array in ...
Uncaught Error: Function name must be a string in...

But, the line

$some_obj->$str();

works perfectly.

Also, both the lines will work, if the function is not defined inside a class.

Anyone knows why this is happening ?

  • 写回答

1条回答 默认 最新

  • dongqin6926 2016-05-22 03:16
    关注

    You should call it this way:

    $some_obj->{$arr['some_index']}();
    

    here's a living example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?