Reputation: 5311
I want to create the setProperties() method inside of the Abstract class which looks like this:
public function setProperties($array = null) {
if (!empty($array)) {
foreach($array as $key => $value) {
if (property_exists($this, $key)) {
$this->{$key} = $value;
}
}
}
}
What I'm not quite sure about is whether I'll be able to use it in the classes that inherit from this Abstract class to set the inherited properties as well as the child class specific.
I'm not sure if I should use any other keyword then $this in the property_exists() function - perhaps there's a way by using late static bindings (static::) keyword?
Upvotes: 0
Views: 864
Reputation: 158090
Your code should basically work. Imagine this simple example what outputs two times true
:
abstract class A {
protected $var1;
public function exists1() {
var_dump(property_exists($this, 'var2'));
}
}
class B extends A {
protected $var2;
public function exists2() {
var_dump(property_exists($this, 'var1'));
}
}
$o = new B();
$o->exists1();
$o->exists2();
As you can see, property_exists()
works when the child class is accessing a member from the parent class and vise versa when the parent class is trying to access a member of the child.
That's one of the basic concepts of abstraction. What you are trying to do is absolutely ok. If you get an error anyway, it must be a little overseen detail
Upvotes: 1
Reputation: 13348
$this
is instance-specific, and as a result, property_exists
will work correctly with child classes.
Upvotes: 1