Question about anonymous methods as members of a class

I am developing a PHP mini-frame, one of which methods creates 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 control flow gen_html_table reaches

 echo $field->getCell($row); 

I get an error: "Calling the undefined method HTMLTableField :: fun ()." But pleasure should be an anonymous method!

+4
source share
6 answers

you cannot use any function through a class property.

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

makes your script run :), checked on php 5.3.1

+1
source

Even shorter and, in my opinion, a more elegant solution:

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

Nothing. I found an ugly but ultimately working solution:

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

I'm not sure what you are trying to accomplish, but is it better for you to use Magic Methods http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods ?

+1
source

One way to do this:

 call_user_func($this->fun, $row) 

I believe this is a style issue, but a lot of time using call_user_func() or call_user_func_array() is considered more powerful than the syntax $func() , and in some cases (like this one) is necessary. It also makes it easy to identify dynamic calls right away.

+1
source

I think you need

 $this->$fun($row) 

but not

 $this->fun($row) 

The first function pointer call is stored in the $fun member variable, and the last one calls the fun() member function, which, as indicated, does not exist.

0
source

Source: https://habr.com/ru/post/1335491/


All Articles