Welcome to Abdul Malik Ikhsan's Blog

Call private/protected method without ReflectionMethod in PHP

Posted in php by samsonasik on July 21, 2019

For whatever reason, you may need to call private/protected method from an object. For example, we have a Foo class with bar method with private modifier like below:

class Foo
{
    private function bar()
    {
        echo 'hit';
    }
}

We need to call bar() method from an instance of Foo class. If you are familiar with ReflectionMethod, you may do this:

$r = new ReflectionMethod($foo = new Foo(), 'bar');
$r->setAccessible(true);
$r->invoke($foo);

There is another way. It is by using invoked of Closure::bindTo() like below:

(function ($foo) {
    $foo->bar();
})->bindTo($foo = new Foo(), Foo::class)($foo);

That’s it!

Tagged with: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: