2012-11-12 47 views
2

有沒有辦法找出類屬性值是來自父類還是子類。PHP:是來自子類或父類的類屬性/常量值

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

您可能需要使用反射來完成此操作。但是,如果您需要在真實應用程序中執行此操作,它看起來很糟糕。 – FtDRbwLXw6

回答

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";