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 class. But, I want to known why setAccessible method can not change the constructor method to be accessible ?
Aucun commentaire:
Enregistrer un commentaire