如何以编程方式从类的方法之一中查找类的公共属性 [英] How to programmatically find public properties of a class from inside one of it's methods
问题描述
我有一个具有公共和受保护属性的类Foo
. Foo
需要有一个非静态方法getPublicVars()
,该方法返回Foo
的所有公共属性的列表(这只是一个例子,我从 outside 知道Foo
调用 get_object_vars()
的对象将完成此操作,并且不需要我的getPublicVars()
方法.)
I've got a class Foo
with public and protected properties. Foo
needs to have a non-static method, getPublicVars()
that returns a list of all the public properties of Foo
(this is just an example, I know from outside the Foo
object calling get_object_vars()
will accomplish this and there is no need for my getPublicVars()
method).
注意:这还必须返回在运行时分配给未在类定义中定义的类实例(对象)的动态声明的属性.
Note: This must also return dynamically declared properties assigned at runtime to the class instance (object) that aren't defined in the class's definition.
这里是例子:
class Foo{
private $bar = '123';
protect $boo = '456';
public $beer = 'yum';
//will return an array or comma seperated list
public function getPublicVars(){
// thar' be magic here...
}
}
$foo = new Foo();
$foo->tricky = 'dynamically added var';
$result = $foo->getPublicVars();
var_dump($result); // array or comma list with 'tricky' and 'beer'
最简单的方法是从一个类的自己的方法中获取对象的所有公共属性,而这些方法的公共和受保护的对象都是可见的?
What is the most concise way to get the only the public properties of an object from inside a class's own methods where both public and protected are visible?
我看过:
- 但这似乎没有解决我的问题,因为它指向从对象外部使用
get_object_vars()
.But this doesn't seem to address my question as it points to using
get_object_vars()
from outside the object.推荐答案
您已经意识到,PHP在
get_object_vars
是作用域敏感的.您只需要 public 对象属性.As you already realized, PHP's build in
get_object_vars
is scope-sensitive. You want the public object properties only.因此从该功能到公开变体的步骤并不大:
So from that function to the public variant is not a large step:
function get_object_public_vars($object) { return get_object_vars($object); }
调用此
get_object_public_vars
只会为您提供公共属性,因为它不在当前对象的范围之内.Calling this
get_object_public_vars
will give you only the public properties then because it is place out of scope of the current object.如果您需要更多细粒度的控制,还可以使用
ReflectionObject
:>If you need more fine-grained control, you can also make use of the
ReflectionObject
:(new ReflectionObject($this))->getProperties(ReflectionProperty::IS_PUBLIC);
这样的好处是您不需要在全局名称空间中引入另一个函数.
Which has the benefit that you don't need to introduce another function in the global namespace.
这篇关于如何以编程方式从类的方法之一中查找类的公共属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!