March 3, 2013

How can I get the child properties without the parent properties?

Question by user1020317

I’ve something like the following:

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

The output is

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

I pressume this is because when get_class_vars(‘b’) is called within a it has access to firstVar, but how can I get the function foo() to output just the class ‘b’ variables, without the parent variables?

Theres a solution on http://php.net/manual/en/function.get-class-vars.php which involves getting the a variables, then getting all a and b variables and then removing the ones that are in both, leaving just the b variables. But this method seems tedious. Is there another way?


Workaround I’m currently using:

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

Answer by Starx

You must be running on lower PHP version. It works fine on codepad on your same code.

Demo: http://codepad.org/C1NjCvfa

However, I will provide you with an alternative. Use Reflection Clases:

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

Preview

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!