[php-src] Issue #10414: Allow for first-class-callables to be created from methods that aren't static, statically

From: Date: Sun, 22 Jan 2023 17:06:53 +0000
Subject: [php-src] Issue #10414: Allow for first-class-callables to be created from methods that aren't static, statically
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-243536@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/10414
Author: ollieread

### Description

This is likely to require an RFC, but here goes.

Currently, if you were to use the first-class-callable syntax to create a closure for a method that
isn't static, statically, you get an error. 

Example code:

```php
class Test {
    public function test(): string { return 'test'; }
 }
 
 $closure = Test::test(...);
 ```

In the above example you receive an error for Test::test() because it isn't a
static method.

I am not suggesting that we get rid of that error completely, but we instead delay it, so instead of
happening at the point of callable/closure creation, it happens when calling.

So, taking the above code, the following would throw an error.

```php
$closure();
```

But the following would not, because the scope of the callable/closure has been set to that of an
instance.

```php
$closure->bindTo(new Test);
$closure();
```

This is particularly annoying when dealing with collections of objects that you want to filter. 

Take the following class.

```php
class Str {
    public function __construct(private string $string){}
    public function upper() { return strtoupper($this->string); }
    public function length() { return strlen($this->string); }
    public function empty() { return empty($this->string); }
}
```

If you had a collection of Str and wanted to filter by whether it is empty you'd
currently have to do the following:

```php
$collection->filter(function (Str $string) {
    return !$string->empty();
});
```

As opposed to:

```php
$collection->filter(Str::empty(...));
```

This would most likely require additional checks in place, perhaps in Closure itself,
that errors when attempting to bind a closure that is a static version of a non-static method, to a
value that isn't an instance.

Like I said, I imagine this will require an RFC, but I think this would make the first-call-callable
feature way more relevant.


Thread (1 message)

  • ollieread
« previous php.bugs (#243536) next »