2012-01-06 202 views
3

是否可以檢查是否存在使用魔術設置器設置的屬性?檢查屬性是否存在

class Test 
{ 
    private $vars; 

    public function __set($key, $value) { 
     $this->vars[$key] = $value; 
    } 

    public function &__get($key) 
    { 
     return $this->vars[$key]; 
    } 
} 

$test = new Test; 

$test->myvar = 'yay!'; 

if (magic_isset($test->myvar)) { 
} 

或者是不可能的,我只需要在我的班級設置另一個功能?

+3

嘗試尋找在__isset http://php.net/manual/en/language.oop5.overloading.php – Damp 2012-01-06 19:31:57

+0

@Damp Eeeck。 OFC。 :P \ – PeeHaa 2012-01-06 19:33:47

+1

沒有真正的@danjordan說試試看php5中的property_exists http://php.net/manual/en/function.property-exists.php – 2013-04-06 20:27:49

回答

7

使用__isset()isset()

public function __isset($key) 
{ 
    return isset($this->vars[$key]); 
} 
$test = new Test; 

$test->myvar = 'yay!'; 

if (isset($test->myvar)) { 

} 
+5

'isset'的行爲與'property_exist'函數不一樣(即,如果一個屬性存在但等於'null'或'false','isset'通常返回'false')。這個解決方案(但也是問題)非常模糊。 – 2013-05-24 06:42:50