php_nub_qq
php_nub_qq

Reputation: 16015

PHP get class initial properties from instance without reflection

I'll try to explain what the problem is with code

class A {
    protected $a;
}

class B extends A {
    protected $b;
}

$b = new B();
$b->c = true;

get_class_properties($b);

I need this function to return me only the properties which the class was declared with, excluding inherited and dynamically created properties. Expected result of the code is

Array (
    [0] => string(1) 'b'
)

Is this possible without the use of reflection classes?

Upvotes: 1

Views: 144

Answers (1)

php_nub_qq
php_nub_qq

Reputation: 16015

I came up with a solution, of course after I posted the question. I'll just add the answer in case anybody is looking for this in future.

Also if anyone has a better solution, please post!

What I came up with is I needed to add an additional method for getting the property names

public function getOwnProperties(){
    return get_class_vars(__CLASS__);
}

So in the example from the question it would look like

class A {
    protected $a;

    public final function getOwnProperties(){
        return get_class_vars(get_called_class());
    }
}

class B extends A {
    protected $b;
}

$b = new B();
$b->c = true;

print_r($b->getOwnProperties());

IMPORTANT

This solution does not satisfy one of the requirements from the question - it gives inherited properties as well.

Upvotes: 2

Related Questions