PHP:在不实例化类的情况下获取所有类属性(公共和私有)的列表

mcm*_*phy 3 php reflection private-members

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

namespace App\Objects;

class POPO  {
    private $foo;
    private $bar;

    // getters and setters //
}
Run Code Online (Sandbox Code Playgroud)

在其他地方,我有一个(详细信息 - 该类做什么并不重要)类需要知道 POPO 属性的名称。POPO 不会传递到此类中,此类也不实例化 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.
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

the*_*nyy 7

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

包含要反映的类名称的字符串或对象。

所以

<?php

class SomeClass
{
    private $member;

    private $othermember;
}

$cls = new ReflectionClass( SomeClass::class );
print_r( $cls->getProperties() );
Run Code Online (Sandbox Code Playgroud)

将打印:

Array
(
    [0] => ReflectionProperty Object
        (
            [name] => member
            [class] => SomeClass
        )
    [1] => ReflectionProperty Object
        (
            [name] => othermember
            [class] => SomeClass
        )
)
Run Code Online (Sandbox Code Playgroud)