Re: Idea: Pure Functions in PHP
| From: | Larry Garfield | Date: | Fri, 25 Sep 2026 21:48:51 +0000 |
| Subject: | Re: Idea: Pure Functions in PHP | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-132645@lists.php.net to get a copy of this message | ||
On Fri, Sep 25, 2026, at 3:02 PM, Marco Pivetta wrote:
> Hey Pedro,
>
> On Fri, 25 Sept 2026 at 21:59, Pedro Veloso
> <contatopedrohalves@gmail.com> wrote:
>> ```php
>> class Ha {
>> private int $a = 1;
>>
>> #[Pure]
>> public function getA(): int {
>> return $this->a;
>> }
>> }
>>
>> new Ha()->getA(); // Fatal error: pure method Ha::getA() accesses $this.
>> ```
>
> Overall, I would also like to see functional purity in PHP, but a n
> instance method is just a function with an implicit additional
>
$this
> argument, and it is pure if it causes no state mutation.
>
> Marco Pivetta
>
> https://mastodon.social/@ocramius
>
> https://ocramius.github.io/
I am also a big fan of functional purity in most forms. However, as noted there's already many
SA tools that support this. (Via @pure or #[Pure]. There's even an unreleased PER from FIG
that has one.). So for this to make sense in the language itself, it needs to offer more benefit
than just "the same thing but in the language."
The OP mentioned possible optimizations or inlining or things like that. At least some of those
would need to be included initially to justify the RFC. Eg, #[Pure, Memoize] to mark it pure and
auto-memoize the function, #[Pure, Inlineable] to allow the compiler/optimizer to compile away the
function call, maybe the function call itself could be made cheaper if we know the function is
pure... there's likely lots of options, but someone with more engine knowledge would need to
say what's feasible. But we would need something.
The other catch is that, as Marco notes, purity is not always trivial to discover. Especially when
passing around objects, if you call a method on the object, it MIGHT mutate something? Who knows?
So defining precisely what we're able to enforce would be important, too.
--Larry Garfield