Question regarding anonymous methods as class members

允我心安 提交于 2019-12-05 16:24:14

you can't use an anynomious function via the class property.

function getCell($row) {
    # This line works
    $fun = $this->fun;
    return $this->alg . $fun($row) . "</td>";
}

makes your script running :), tested on php 5.3.1

Lukáš Krejčí

There is even shorter and in my opinion more elegant solution:

function getCell($row) {
    return "{$this->alg}{$this->fun->__invoke($row)}</td>";
}

Never mind. I found an ugly, but ultimately working solution:

$func = $this->fun;
return "{$this->alg}{$func($row)}</td>";

I'm not sure what you are try to accomplish but are you not better off using Magic Methods http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods?

One way to do this is:

call_user_func($this->fun, $row)

I suppose it's a matter of style, but a lot of time using call_user_func() or call_user_func_array() is considered cleaner than $func() syntax, and in some cases (such as this one), necessary. It also makes it easier to spot dynamic calls right away.

I think you need

$this->$fun($row)

rather than

$this->fun($row)

The former calls the function pointer stored in the member variable $fun, while the latter calls the member function fun(), which as pointed out does not exist.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!