dsb238100 2012-09-20 18:39
浏览 19
已采纳

获取用户在类外定义的所有变量的列表

i have something like this:

class foo
{
   //code
}

$var = new foo();
$var->newVariable = 1; // create foo->newVariable
$var->otherVariable = "hello, im a variable";  //create foo->otherVariable

i can get in class foo a list of all variables defined outside by user (newVariable, otherVariable,etc)? Like this:

class foo
{
   public function getUserDefined()
   {
      // code

   }
}

$var = new foo();
$var->newVariable = 1; // create foo->newVariable
$var->otherVariable = "hello, im a variable";  //create foo->otherVariable
var_dump($var->getUserDefined()); // returns array ("newVariable","otherVariable");

Thanks!.

  • 写回答

4条回答 默认 最新

  • dta38159 2012-09-20 18:42
    关注

    Yes, using get_object_vars() and get_class_vars():

    class A {
    var $hello = 'world';
    }
    $a = new A();
    $a->another = 'variable';
    echo var_dump(get_object_vars($a));
    echo '<hr />';
    // Then, you can strip off default properties using get_class_vars('A');
    $b = get_object_vars($a);
    $c = get_class_vars('A');
    foreach ($b as $key => $value) {
        if (!array_key_exists($key,$c)) echo $key . ' => ' . $value . '<br />';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?