tags:

views:

27

answers:

3

i have a class that extends another.

when i iterate the current object i get all properties, even those from the superclass.

i only want to iterate through the current object. how could i do that?

foreach($this as $key => $value) {
    echo $key . ': ' . $value;
}
+1  A: 

Very interesting question.

I will highly recommend to read the examples here - http://dsl093-056-122.blt1.dsl.speakeasy.net/edu/oreilly/Oreilly_Web_Programming_bookshelf/webprog/php/ch06_05.htm they will give you greater insight about Introspection. The reference about those methods used is here - http://www.php.net/manual/en/ref.classobj.php


Here is the function with a test case. It will work only in PHP 5+ as it uses Reflection which was not available before that. You can read more about Reflection here - http://www.php.net/manual/en/class.reflectionclass.php

<?php

echo '<pre>';

class A {
    public $pub_a = 'public a';
    private $priv_a = 'private a';
}

class B extends A {
    public $pub_b = 'public b';
    private $priv_b = 'private b';
}

$b = new B();

print_r(getChildrenProperties($b));

function getChildrenProperties($object) {
    $reflection = new ReflectionClass(get_class($object));
    $properties = array();

    foreach ($reflection->getProperties() as $k=>$v) {
        if ($v->class == get_class($object)) {
            $properties[] = $v;
        }
    }

    return $properties;
}
Ivo Sabev
a little hack but the code worked. thanks for digging into it!
never_had_a_name
+1  A: 

You can also try and use PHP Reflection http://php.net/manual/en/book.reflection.php

I guess what you can do using @Ivo Sabev answer is:

 $properties = get_class_vars(ChildClass);
 $bproperties = get_class_vars(ParentClass);

And now iterate over all $properties that does not appear in $bproperties.

aviv
Yeah that is the idea, but these functions actually dont give you the private properties. I am not looking at the ReflectionClass and might write a small function to do the trick.
Ivo Sabev
A: 

The get_class_vars manual page contains an example of doing this in the user comments section (very top).

http://us.php.net/manual/en/function.get-class-vars.php

webbiedave
but that gets only the Class variables, and not the object variables i guess?
never_had_a_name