Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.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
PHP:使用私有构造函数访问对象的方法_Php - Fatal编程技术网

PHP:使用私有构造函数访问对象的方法

PHP:使用私有构造函数访问对象的方法,php,Php,我有一门课: class A { private function __construct() { throw new Exception('thrown'); } public function A() { return array('a', 'b', 'c'); } public static function I() { return new A(); } } 问题

我有一门课:

class A
{
    private function __construct()
    {
        throw new Exception('thrown');
    }

    public function A()
    {
        return array('a', 'b', 'c');
    }

    public static function I()
    {
        return new A();
    }
}
问题:如何在屏幕上精确打印上面数组中的“b”? 条件: 我不能改变这门课。 我只能使用一个命令(代码中至少有一行)

请尝试以下方法:

$reflection = new ReflectionClass("A");
$instance = $reflection->newInstanceWithoutConstructor();

$instance

上使用类的方法首先为什么要使用这个类?您试图实现什么?由于您根本无法实例化该类,也无法静态调用A()方法,因此您无法访问类中的任何内容,这使得它对任何内容都毫无用处您可以使用反射绕过这些问题,但该类基本上仍然是无用的
echo(新的ReflectionClass('A'))->newInstancewithout构造函数()->A()[1]只需扩展该类并向子类添加公共构造函数。并像往常一样调用该方法。