子类中的 PHP get_class() 功能


PHP get_class() functionality in child classes

我需要检查一个属性是否存在并且有效:

class someClass {
  protected $some_var
  public static function checkProperty($property) {
    if(!property_exists(get_class()) ) {
      return true;
    } else return false;
  }
}

但是现在当我尝试扩展类时,它不再起作用了。

class someChild extends someClass {
  protected $child_property;
}

someChild::checkProperty('child_property'); // false

如何获得所需的功能?我尝试用$thisselfstatic替换get_class(),没有任何效果。

我相信

我已经找到了正确的答案。对于静态方法,请使用 get_called_class()

也许$this适用于对象方法。

如何对照 get_class() 和 get_parent_class() 检查property_exists?但是,对于更多嵌套类,您必须递归检查这些类。

public static function checkProperty($property)
{
    if (property_exists(get_class(), $property)
        or property_exists(get_parent_class(), $property))
    {
        return true;
    }
    else return false;
}

(对不起,但我更喜欢奥尔曼风格;-))

以下作品:

<?php
class Car
{
    protected $_var;
    public function checkProperty($propertyName)
    {
        if (!property_exists($this, $propertyName)) {
            return false;
        }
        return true;
    }
}
class BMW extends Car
{
    protected $_prop;
}
$bmw = new BMW();
var_dump($bmw->checkProperty('_prop'));

@param $class 要测试的类的类名或对象