Skip to content

Instantly share code, notes, and snippets.

@alan-ps
Last active August 3, 2019 15:12
Show Gist options
  • Save alan-ps/730ea3c61a34bea98fec0ecdbca2e24a to your computer and use it in GitHub Desktop.
Save alan-ps/730ea3c61a34bea98fec0ecdbca2e24a to your computer and use it in GitHub Desktop.
Call private methods and private properties from outside a class in PHP.
<?php

class MyClass {

  private function somePrivateMethod() {
    echo 'This method is private!';
  }

}
Reflection API
<?php
$MyObject = new MyClass();
$reflector = new ReflectionObject($MyObject);
$method = $reflector->getMethod('somePrivateMethod');
$method->setAccessible(true);
$method->invoke($MyObject); // This method is private!
Closure

Usind bind method:

$MyObject = new MyClass();

$closureBind = Closure::bind(function(MyClass $myClass) {
  return $myClass->somePrivateMethod();
}, null, $MyObject);

$privateProperty = $closureBind($MyObject); // This method is private!

Using call method:

$MyObject = new MyClass();

(function () {
    return $this->somePrivateMethod();
})->call($MyObject); // This method is private!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment