DEV Community

Discussion on: All flavors of PHP 8 getters

Collapse
kastaneda profile image
Карлос Кастанеда ✳️

One more way: use Closure::bind().

Collapse
bdelespierre profile image
Benjamin Delespierre Author

Good call 😉 I'm adding it!

Collapse
doekenorg profile image
Doeke Norg • Edited
class SomeClass
{
    private string $title = 'Some Class Title';
}

$some = new SomeClass();

$closure = function() {
    return $this->title;
};

$get_title = $closure->bindTo($some, $some);

echo $get_title(); // Some Class Title
Enter fullscreen mode Exit fullscreen mode

I think this is the idea. Very nasty, but indeed effective :-)

::bind() is the static variant of ->bindTo()

For those that want an example from the wild, checkout this NullAdapter from Symfony. It uses Closure::bind() to wrap items from the cache into CacheItem DTO's.

Collapse
bdelespierre profile image
Benjamin Delespierre Author

Interesting way of breaking encapsulation 👍