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

前端 未结 3 948
醉梦人生
醉梦人生 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:21

    According to this article (written by Vance Lucas), you can create a new call scope inside your "Foo" class definition using an "anonymous" function, and then you can call get_object_vars() from within. This allow you to get only the public properties from inside your class, even if these have been created dynamically later from the outside.

    So adapted to your example it would be:

    tricky = 'dynamically added var';
    
     $result = $foo->getPublicVars();  
     print_r($result);
    

    and the output will be:

    Array
    (
        [beer] => yum
        [tricky] => dynamically added var
    )
    

    There is a second example in the article mentioned above that shows another way to do the same using the so-called "closures" (from php 5.3) but for some reason it doesn't work for me with php v5.4 so the private and protected properties remains included in the resulting array.

提交回复
热议问题