2

有没有办法找出类属性值是来自父类还是子类。

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 中而不是在父级中声明。

4

1 回答 1

0

这应该可以解决您的部分问题。这段代码运行良好的条件是在子类中,redefine 变量的默认值必须与父类不同。

/**
 * @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";
于 2012-11-12T03:06:31.680 回答