1

我有以下内容:

class a {

    private $firstVar;  

    function foo(){

        print_r( get_class_vars( 'b' ) );   
    }
}


class b extends a{

    public $secondVar;  

}

a::foo();
print_r( get_class_vars( 'b' ) );

输出是

Array ( [secondVar] => [firstVar] => ) 
Array ( [secondVar] => )

我认为这是因为当在 a 中调用 get_class_vars('b') 时,它可以访问 firstVar,但是如何让函数 foo() 只输出类 'b' 变量,而不输出父变量?

http://php.net/manual/en/function.get-class-vars.php上有一个解决方案,其中涉及获取 a 变量,然后获取所有 a 和 b 变量,然后删除两者中的变量,留下只是 b 变量。但这种方法似乎很乏味。还有其他方法吗?


我目前正在使用的解决方法:

class a {

    private $firstVar;  

    function foo(){

        $childVariables = array();

        $parentVariables = array_keys( get_class_vars( 'a' ));

        //array of 'a' and 'b' vars
        $allVariables = array_keys( get_class_vars( get_class( $this ) ) );

        //compare the two
        foreach( $allVariables as  $index => $variable ){

            if( !(in_array($variable, $parentVariables))){

                //Adding as keys so as to match syntax of get_class_vars()
                $childVariables[$variable] = "";
            }
        }

        print_r( $childVariables );
    }
}


class b extends a{

    public $secondVar;  

}

$b = new b;
$b->foo();
4

1 回答 1

2

您必须在较低的 PHP 版本上运行。它在您的相同代码上的键盘上运行良好。

演示:http ://codepad.org/C1NjCvfa

但是,我将为您提供另一种选择。使用反射类:

public function foo()
{
  $refclass = new ReflectionClass(new b());
  foreach ($refclass->getProperties() as $property)
  {
    echo $property->name;
    //Access the property of B like this
  }
}

Preview

于 2013-03-03T05:00:58.887 回答