Iterate only through existing properties of objects, not from the parent class?

I have a class that extends another.

when I repeat the current object, I get all the properties, even those from the superclass.

I only want to iterate over the current object. How can i do this?

foreach($this as $key => $value) {
    echo $key . ': ' . $value;
}
+3
source share
3 answers

Very interesting question.

I highly recommend reading the examples here - http://dsl093-056-122.blt1.dsl.speakeasy.net/edu/oreilly/Oreilly_Web_Programming_bookshelf/webprog/php/ch06_05.htm , which will provide you with a deeper understanding of introspection. A link to these used methods here is http://www.php.net/manual/en/ref.classobj.php


. PHP 5+, Reflection, . Reflection - 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;
}
+1

PHP Reflection http://php.net/manual/en/book.reflection.php

, , @Ivo Sabev:

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

$, $bproperties.

+1

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

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

0
source

Source: https://habr.com/ru/post/1740738/


All Articles