PHP:是子类或父类的类属性/常量值

时间:2012-11-12 02:41:24

标签: php oop

有没有办法确定类属性值是来自父类还是子类。

class A {
   public static $property1 = "X";
   public static $property2 = "Y"; 

   public static isFrom($propertyName) {
      /// what should be here?
   }  
}

class B extends A {
   public static $property1 = "Z";
}

class C extends B {
}

C::isFrom("property1"); /// should return "CLASS B";
C::isFrom("property2"); /// should return "CLASS A";

关于类常量的相同问题。

是否有可能找到声明常量的确切类(访问子类C)?函数定义(“C :: SomeConstant”);如果SomeConstant在A或B或C中声明,则返回true。我正在寻找解决方案,以确定是否在C类中声明常量而不是在父项中。

1 个答案:

答案 0 :(得分:0)

这应解决你问题的一部分。此代码运行良好的条件是在子类中,重定义变量必须具有与父类不同的默认值。

/**
 * @author Bang Dao
 * @copyright 2012
 */

class A {
   public static $property1 = "X";
   public static $property2 = "Y"; 

    public static function isFrom($propertyName) {
        $class = get_called_class();
        $vars = array();
        do{
            $_vars = get_class_vars($class);
            $vars[$class] = $_vars; //for other used
            $class = get_parent_class($class);
        } while($class);

        $vars = array_reverse($vars);
        $class = -1;
        foreach($vars as $k => $_vars){
            if(isset($_vars[$propertyName])){
                if($class == -1)
                    $class = $k;
                else{
                    if($_vars[$propertyName] !== $vars[$class][$propertyName])
                        $class = $k;
                }
            }
        }

        return $class;
    }  
}

class B extends A {
   public static $property1 = "Z";
}

class C extends B {
}

echo C::isFrom("property1"); /// should return "CLASS B";
echo '<br />';
echo C::isFrom("property2"); /// should return "CLASS A";