doufan6544 2017-01-28 14:42
浏览 165

为什么setAccessible方法无法改变php中可访问的构造函数方法?

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 ?

  • 写回答

1条回答 默认 最新

  • dongpu2694 2017-06-10 15:45
    关注

    $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*/]);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line