2013-08-07 43 views
1
<?php 

    class test{ 
     private $s; 

     function test(){ 
     $this->d="test"; 
     } 
    } 

    $c=new test(); 

?> 

我的設置是error_reporting = E_ALL | E_STRICTPHP引用未定義類屬性不會引發錯誤

和PHP還是沒有注意到這個問題!我能做些什麼來讓php爲這些類型的錯誤拋出異常

+0

可能重複[爲什麼沒有調用未定義的函數PHP錯誤?](http://stackoverflow.com/questions/7897339/why-no-php-error-on-call-to-undefined-function) –

+0

要顯示錯誤,display_errors應該打開(display_errors = On) – Duleendra

回答

0

訪問不存在被認爲是不好(E_NOTICE)的屬性,同時設定一個簡單的創建同名的公共財產。

<?php 
error_reporting(E_ALL); 

class foo 
{ 
    public function __construct() 
    { 
    var_dump($this->a); 
    $this->b = true; 
    } 
} 

new foo; 

會給你:

Notice: Undefined property: foo::$a on line 7 
NULL 

如果你真的想阻止這種行爲,你可以掛接到魔術__get__set的方法是所謂當一個未知的屬性進行訪問:

<?php 
class foo 
{ 
    public function __construct() 
    { 
    $this->doesNotExist = true; 
    } 

    public function __set($name, $val) 
    { 
    throw new Exception("Unknown property $name"); 
    } 
} 

如果你想一遍又一遍地做這個:

<?php 
trait DisableAutoProps 
{ 
    public function __get($name) 
    { 
    throw new Exception("Unknown property $name"); 
    } 
    public function __set($name, $val) 
    { 
    throw new Exception("Unknown property $name"); 
    } 
} 

class foo 
{ 
    use DisableAutoProps; 

    public function __construct() 
    { 
    $this->doesNotExist = true; 
    } 
} 
0

它不是一個錯誤。如果你試圖調用一個未定義的方法,php會變得瘋狂,但在這種情況下,php很樂意將該聲明作爲聲明。

<?php 

    class test{ 
     private $s; 

     function test(){ 
     $this->d="test"; 
     } 
    } 

    $c=new test(); 
echo $c->d; //"test" 

?>