Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/255.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么setAccessible方法不能将构造函数方法更改为在php中可访问?_Php_Reflection_Constructor - Fatal编程技术网

为什么setAccessible方法不能将构造函数方法更改为在php中可访问?

为什么setAccessible方法不能将构造函数方法更改为在php中可访问?,php,reflection,constructor,Php,Reflection,Constructor,当我尝试在PHP中使用反射API来创建新的singleton模式类实例时,由于非公共构造函数,我失败了 简单代码: <?php class Singleton{ private static $instance = null; protected function __construct(array $config = []){ //do something... } public static function getInstance(

当我尝试在PHP中使用反射API来创建新的singleton模式类实例时,由于非公共构造函数,我失败了

简单代码:

<?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 ...
}

$class->getConstructor()
返回ReflectionMethod,并且
setAccessible(true)
允许调用该方法,但只能从ReflectionMethod实例调用。在ReflectionClass级别,构造函数保持私有

要想做你想做的事,你可以尝试以下方法:

$reflection = new ReflectionClass(MySingletonClass::class);
$constructor = $reflection->getConstructor();
$constructor->setAccessible(true);

$mySingleton =  $reflection->newInstanceWithoutConstructor();
$constructor->invokeArgs($mySingleton, [/*your arguments*/]);

$class->getConstructor()
返回ReflectionMethod,
setAccessible(true)
允许调用该方法,但只能从ReflectionMethod实例调用。在ReflectionClass级别,构造函数保持私有

要想做你想做的事,你可以尝试以下方法:

$reflection = new ReflectionClass(MySingletonClass::class);
$constructor = $reflection->getConstructor();
$constructor->setAccessible(true);

$mySingleton =  $reflection->newInstanceWithoutConstructor();
$constructor->invokeArgs($mySingleton, [/*your arguments*/]);