Check variable is public php

后端 未结 3 1337
借酒劲吻你
借酒劲吻你 2021-01-29 10:49

I want to check if a local variable in a class is public or private. The reason is to create a function like this:

function ToArray() {
  $arr = array();
  forea         


        
相关标签:
3条回答
  • 2021-01-29 10:54

    From the PHP documentation,

    $foo = new Foo();
    
    $reflect = new ReflectionClass($foo);
    $props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
    
    foreach ($props as $prop) {
        print $prop->getName() . "\n";
    }
    
    var_dump($props);
    
    0 讨论(0)
  • 2021-01-29 10:54

    To get a list of all public attributes call get_object_vars().

    (Hint: calling it by the object itself will return all attributes.)

    0 讨论(0)
  • 2021-01-29 11:14

    Make sure to follow some naming convention with your private variables (like i prepend them with _)

    Then just return those variables that do not have _ in the beginning of their key.

    0 讨论(0)
提交回复
热议问题