Skip to content

Instantly share code, notes, and snippets.

@vlakoff
Created March 19, 2016 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlakoff/f623337bb00e113330cb to your computer and use it in GitHub Desktop.
Save vlakoff/f623337bb00e113330cb to your computer and use it in GitHub Desktop.
Call private/protected PHP methods. Danger zone. Don't do this at home.
<?php
// we'll do nasty things to this instance
$instance = new Foo;
// pass instance or class name
$method = new ReflectionMethod($instance, 'privateMethod');
$method = new ReflectionMethod('Foo', 'privateMethod');
// milkshakes to the yard
$method->setAccessible(true);
// pass context then arguments as variadic
$method->invoke($instance, 'arg1', 'arg2');
$method->invoke(new Foo, 'arg1', 'arg2');
// arguments as array
$method->invokeArgs($instance, ['arg1', 'arg2']);
// summary
$method = new ReflectionMethod($instance, 'privateMethod');
$method->setAccessible(true);
$method->invoke($instance, 'arg1', 'arg2');
// now with static method
$method = new ReflectionMethod('Foo', 'privateStaticMethod');
$method->setAccessible(true);
$method->invoke(null, 'arg1', 'arg2'); // here we pass null for context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment