检查子类是否存在变量


Checking if variable exists for child class

我正在为我的父类创建全局资源库和getter,因为我不想为每个子类变量创建它们(但我偶尔会覆盖父全局setter/getter)。

我正在使用__call,我正在解析方法名称,如下所示:

if (strtolower(substr($method, 0, 3)) == "set") {
  $variable = strtolower(substr($method, 3));
}

问题是我如何检查是否为子类(扩展主类的子类)设置了$variable;

如果我这样做:

if ($this->$variable)
我想它首先检查它是否存在于

子类,然后检查它是否存在于主类。我只想检查子班,可以吗?

我知道有父母::但是孩子有等价物吗?

编辑:人们不明白我在问什么。我知道如何检查该属性是否存在。我想知道的是如何检查 CHILD 类的属性是否存在,而不是 MAIN 类的属性。(类子扩展主)

在通常情况下,有isset()函数,但不适合这种情况。请改用 property_exists():

class Foo
{
    public $pub = null;
}
$obj = new Foo();
var_dump(isset($obj->pub), property_exists('Foo', 'pub')); //false, true

-那是因为如果 proprty 存在,但为 null,isset()将返回 false - 当它不存在时,您将无法区分大小写。

如果它是关于动态属性 - 那么你应该将对象而不是类名传递给property_exists()因为属性可能在类中不存在,然后动态添加到对象中。

现在,如果我们说哪个在声明属性,你可以在 PHP 中使用 Reflection,如下所示:

class Foo
{
    public $pub = null;
}
class Bar extends Foo
{
}
$obj = new Bar();
$ref = new ReflectionObject($obj);
var_dump($ref->getProperty('pub')->getDeclaringClass()->getName() == 'Bar');//false
var_dump($ref->getProperty('pub')->getDeclaringClass()->getName() == 'Foo');//true

你为什么不使用isset

if (isset($this->$variable))
这对

我有用:

if(property_exists($get_class($this),$variable)){}