Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php: how to make private static method to public, and class cannot be insantized?

Tags:

php

reflection

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?

like image 320
John Smith Avatar asked Oct 09 '14 23:10

John Smith


People also ask

Can static method be private PHP?

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.

Can a static method instantiate 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.

How use $this in static method in PHP?

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.

Can static methods be public or private?

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.


1 Answers

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);
  ...
}
like image 88
mpen Avatar answered Oct 08 '22 21:10

mpen