abstract class MyClass
{
private static makeMePublic()
{
}
}
I want to make MyClass::makeMePublic method to be callable from the outside. I saw a solution here: Best practices to test protected methods with PHPUnit but that requires the class to be instantized. In this case its not possible. So, how to make "public" this method?
So it goes into a private static method that the non-private factory methods call. Visibility (private versus public) is different from class method (i.e. static) versus instance method (non-static). A private static method can be called from a public method - static or not - but not from outside the class.
What's a static method? In the same way that a static variable is associated with the class as a whole, so is a static method. In the same way that a static variable exists before an object of the class is instantiated, a static method can be called before instantiating an object.
You can't use $this inside a static function, because static functions are independent of any instantiated object. Try making the function not static. Edit: By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.
Static methods can be public or private. The static keyword is placed right after the public/private modifier and right before the type of variables and methods in their declarations.
The docs say you can just pass null
as the first param to invokeArgs
to execute a static method.
protected static function getMethod($name) {
$class = new ReflectionClass('MyClass');
$method = $class->getMethod($name);
$method->setAccessible(true);
return $method;
}
public function testMakeMePublic() {
$foo = self::getMethod('makeMePublic');
$foo->invokeArgs(null, $args);
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With