gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:28:48 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com