PHP:在不实例化 class 的情况下获取所有 Class 属性(public 和私有)的列表

PHP: Get list of all Class Properties (public and private) without instantiating class

我有一个 POPO(普通旧 PHP 对象):

namespace App\Objects;

class POPO  {
    private $foo;
    private $bar;

    // getters and setters //
}

在其他地方,我有一个(详细信息 - class 做什么并不重要)class 需要知道 POPO 属性的名称。 POPO 未传递到此 class,此 class 也不实例化 POPO 或关心其属性的值。

class POPODetails  {
    private $POPOclassName = "App\Object\POPO";  //determined programatically elsewhere.

    public getProperties(): array  {
        return get_class_vars($this->POPOClassName);  //this will only return public properties.
    }
}

要使用 get_object_vars,我需要传入一个实例化对象,否则我不需要它,并且仍然只会获得 public 属性。我可以使用 ReflectionClass::getProperties(),但还需要传入一个实例化对象。

那么,有没有一种方法可以仅使用完全限定的 Class 名称来获取 class 变量的列表?

您仍然可以使用 ReflectionClass,php.net 告诉我们以下有关构造函数参数的信息:

Either a string containing the name of the class to reflect, or an object.

所以

<?php

class SomeClass
{
    private $member;

    private $othermember;
}

$cls = new ReflectionClass( SomeClass::class );
print_r( $cls->getProperties() );

将打印:

Array
(
    [0] => ReflectionProperty Object
        (
            [name] => member
            [class] => SomeClass
        )
    [1] => ReflectionProperty Object
        (
            [name] => othermember
            [class] => SomeClass
        )
)