2016-03-29 64 views
1

如何在類中從類中遍歷所有公共變量?遍歷所有公共變量並將NULL值轉換爲空字符串

如何獲取公共變量?

private function translate_null_values_to_strings(){ 
    foreach($this->public_vars as $key => $value){ 
     if(is_null($this->$key)) $this->$key = ''; 
    } 
} 
+0

http://stackoverflow.com/questions/3309320/php-get-classes - 公共變量 – vaso123

+1

['ReflectionClass :: getProperties'](http://php.net/manual/en/reflectionclass.getproperties.php)'(ReflectionProperty :: IS_PUBLIC)' –

+0

我會避免這樣做..有東西錯誤在您的應用程序中,如果對象有一些屬性設置爲您不想以後的值.. –

回答

3

使用Reflection。我修改從PHP手冊爲例來得到你想要的:

class Test 
{ 
    public $public1 = 'public 1'; 
    public $public2 = ''; 
    public $public3 = 'public 3'; 
    private $private1 = 'private 1'; 

    public function __construct() 
    { 
     $reflect = new ReflectionObject($this); 
     foreach ($reflect->getProperties(ReflectionProperty::IS_PUBLIC) as $prop) 
     { 
      $propName = $prop->getName(); 
      echo $propName." --> ". $this->$propName . "\n"; 
     } 
    } 
} 

$ob = new Test(); 

輸出:

public1 --> public 1 
public2 --> 
public3 --> public 3 
+1

完美答案bro +1。 – GuRu