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

标签 php reflection private-members

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

namespace App\Objects;

class POPO  {
    private $foo;
    private $bar;

    // getters and setters //
}

在其他地方,我有一个(细节——这个类做什么并不重要)类需要知道 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.
    }
}

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

那么,有没有办法只使用完全限定的类名来获取类变量列表?

最佳答案

您仍然可以使用 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
        )
)

关于PHP:在不实例化类的情况下获取所有类属性(公共(public)和私有(private))的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52416094/

相关文章:

javascript - 如何正确评估字符串变量作为 jQuery.post() 中的数据

java - 访问该类的一般对象上的类变量

java - 为什么反射找不到带有 boolean 参数的方法?

C++多重继承私有(private)成员模糊访问

C++选择排序——插入方法和私有(private)变量

php - 如何使用 PHP if/else 更改 CSS 链接文档?不显示错误消息

php - 使用表单中的 session

reflection - Sun JVM 在运行时创建 sun.reflect.DelegatingClassLoader 的实例是什么?

c++ - 试图访问一个类的私有(private)成员以解决重载是否是不正确的?

php - 为 Symfony 1.4 设置第一个 schema.yml