代码之家  ›  专栏  ›  技术社区  ›  Rene Terstegen

如何找到所有非静态类属性

  •  1
  • Rene Terstegen  · 技术社区  · 14 年前

    我想从一个类中获取所有非静态类变量。我的问题是在“非静态”部分。以下内容:

    foreach(array_keys(get_class_vars(get_called_class())) AS $key) {
        echo $key;
    }
    

    如何确定$key是静态属性还是非静态属性。我知道我可以试试这样:

    @$this->$key
    

    但一定有更好的方法来检验这一点。

    有人吗?

    2 回复  |  直到 14 年前
        1
  •  4
  •   user187291    13 年前

    这个代码是我的解决方案。

    $ReflectionClass = new \ReflectionClass(get_called_class());
    
    $staticAttributes = $ReflectionClass->getStaticProperties();
    $allAttributes = $ReflectionClass->getProperties();
    
    $attributes = array_diff($staticAttributes, $allAttributes);
    
        2
  •  1
  •   Mark Baker    14 年前
    class testClass
    {
        private static $staticValPrivate;
    
        protected static $staticValProtected;
    
        public static $staticValPublic;
    
        private $valPrivate;
    
        protected $valProtected;
    
        public $valPublic;
    
        public function getClassProperties()
        {
            return get_class_vars(__CLASS__);
        }
    
        public function getAllProperties()
        {
            return get_object_vars($this);
        }
    
    }
    
    $x = new testClass();
    
    var_dump($x->getClassProperties());
    echo '<br />';
    
    var_dump($x->getAllProperties());
    echo '<br />';
    
    var_dump(array_diff_key($x->getClassProperties(),$x->getAllProperties()));