PHP:在从Child类中调用的Abstract方法内部调用property_exists()函数


PHP : call property_exists() function inside of the Abstract method called from within the Child class

我想在抽象类中创建setProperties()方法,它看起来像这样:

public function setProperties($array = null) {
        if (!empty($array)) {
            foreach($array as $key => $value) {
                if (property_exists($this, $key)) {
                    $this->{$key} = $value;
                }
            }
        }
    }

我不太确定的是,我是否能够在从这个抽象类继承的类中使用它来设置继承的属性以及特定于子类的属性。

我不确定我是否应该在property_exists()函数中使用其他关键字$this——也许有一种方法可以使用后期静态绑定(static::)关键字?

您的代码基本上应该可以工作。想象一下这个简单的例子,输出两次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();

正如您所看到的,当子类从父类访问成员时,property_exists()起作用,反之亦然,当父类试图访问子类的成员时。

这是抽象的基本概念之一。你试图做的是完全可以的。如果你无论如何都得到了一个错误,它一定是一个有点监督的细节

$this是特定于实例的,因此,property_exists将与子类一起正确工作。