Search code examples
phpanonymous-methods

Question regarding anonymous methods as class members


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

However, when the flow of control of gen_html_table reaches

echo $field->getCell($row);

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


Solution

  • 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