When I tried to use Reflection API to new instance of singleton pattern class in PHP, I failed, due to non-public construct function.
simple code:
<?php
class Singleton{
private static $instance = null;
protected function __construct(array $config = []){
//do something...
}
public static function getInstance(array $config = []){
$className = get_called_class();
if (!isset(self::$instance[$className])){
self::$instance[$className] = new static($config);
}
return self::$instance[$className];
}
}
class likeDB extends Singleton{
//...
}
function callbackRF($className, $methodName, array $args = [], array $params = []){
//do something...
$class = new ReflectionClass($className);
//throw Exception
$instance = $class->newInstanceArgs($args);
//do something ...
}
And then, I tried to use $class->getConstructor()->setAccessible(true) before calling newInstanceArgs method. It also failed and the exception message was the same.
Now, I known these code could not get right instance of some object. But, I want to known why setAccessible method can not change the constructor method to be accessible ?
$class->getConstructor()
returns a ReflectionMethod and setAccessible(true)
allows to invoke the method but only from the ReflectionMethod instance. At the ReflectionClass level, the constructor remains private.
To do what you want, you can try something like this:
$reflection = new ReflectionClass(MySingletonClass::class);
$constructor = $reflection->getConstructor();
$constructor->setAccessible(true);
$mySingleton = $reflection->newInstanceWithoutConstructor();
$constructor->invokeArgs($mySingleton, [/*your arguments*/]);