I'm running PHP 5.5.9 and I'm getting a parsing error that I haven't a clue how to resolve. Here's an extremely contrieved example of the technique I'm trying to employ:-
<?php
class NumberDisplayer {
var $numbers = [];
function __invoke($n) {
array_push($this->numbers, $n);
return $this;
}
function display() {
foreach ($this->numbers as $number) {
echo "$number, ";
}
}
}
((new NumberDisplayer())
(5)
(10)
(14)
(20)
(11)
->display());
?>
That yields:-
Parse error: syntax error, unexpected '(' in <documents>/index.php on line 18
Such a pointless example could obviously be solved via better means, but my question is how to make this technique work in situations where it's a good fit.
My reasoning is as follows: new NumberEchoer()
evaluates to an instance of NumberEchoer
, which itself is callable due to __invoke
. Because of this, I should be able to invoke the expression, which itself returns $this which is also invokable, and so on and so forth. At the end of the expression, I invoke the display
method which does the displaying.
I also tried to pack the whole expression onto a single line, but the elimination of the newlines didn't fix anything.
I seem to be able to store NumberDisplayer
into a variable and invoke the variable manually on every line, but it makes the code far less readable.
How can this idiom of chaining magic methods be done in a readable fashion?