How to programmatically find public properties of a class from inside one of it's methods

前端 未结 3 951
醉梦人生
醉梦人生 2021-02-12 20:54

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

3条回答
  •  别跟我提以往
    2021-02-12 21:08

    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);
    }
    

    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.

    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.

提交回复
热议问题