php – 关于匿名方法作为类成员的问题
作者:互联网
我正在开发一个PHP迷你框架,其中一个方法是从一个对象数组构建一个HTML表:
class HTMLTableField {
private $hdr;
private $alg;
private $fun;
function __construct($descr, $align, $apply) {
# fun must be an anonymous function
$this->hdr = '<th>' . htmlentities($descr) . "</th>\n";
$this->alg = "<td style=\"text-align: {$align}\">";
$this->fun = $apply;
}
function getHeader() {
return $this->hdr;
}
function getCell($row) {
# This line fails
return "{$this->alg}{$this->fun($row)}</td>";
}
}
function gen_html_table($rows, $fields) {
# $fields must be an array of HTMLTableField objects
echo "<table>\n<thead>\n<tr>\n";
foreach ($fields as $field)
echo $field->getHeader();
echo "</tr>\n</thead>\n<tbody>\n";
foreach ($rows as $row) {
echo "<tr>\n";
foreach ($fields as $field)
echo $field->getCell($row);
echo "</tr>\n";
}
echo "</tbody>\n</table>\n";
}
但是,当gen_html_table的控制流程到达时
echo $field->getCell($row);
我收到一个错误:“调用未定义的方法HTMLTableField :: fun().”但有趣的应该是一个匿名的方法!
解决方法:
你不能通过class属性使用anynomious函数.
function getCell($row) {
# This line works
$fun = $this->fun;
return $this->alg . $fun($row) . "</td>";
}
让你的脚本运行:),在php 5.3.1上测试
标签:php,anonymous-methods 来源: https://codeday.me/bug/20190531/1188836.html