关于匿名方法作为类成员的问题 [英] Question regarding anonymous methods as class members

查看:74
本文介绍了关于匿名方法作为类成员的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个PHP微型框架,其中一种方法是根据对象数组构建HTML表:

I am developing a PHP mini-framework, one of whose methods builds an HTML table from an array of objects:

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()。

I get an error: "Call to undefined method HTMLTableField::fun()." But fun is supposed to be an anonymous method!

推荐答案

您不能通过class属性使用任意函数。

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>";
}

使脚本运行:),已在php 5.3.1上进行了测试

makes your script running :), tested on php 5.3.1

这篇关于关于匿名方法作为类成员的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆