2014-05-08 145 views
0

我對於在類中使用PHP相當新穎,並想知道是否有更好的方法來處理我正在做的事情。基本上,我正在尋找處理用戶錯誤的最佳方式(如「該用戶名被採取」等)。類中的全局變量

我在做什麼..

在的init.php

global $errors; 
$errors = array(); 
require ... 

在classname.php

class Test { 
public function myFunction($username) { 

    if ... { 
    //Do Something 
    global $errors; 
    $this->errors = $errors[] = "Username already in use!"; 
    } 

    else ... { 
    global $errors; 
    $this->errors = $errors[] = "Username already in use!"; 
    } 
} 
public function .... {} 
} 

基本上是有辦法,我可以使用全局數組,而不必每次重寫全局$錯誤?不得不重複它只是沒有效率,在我的情況通常意味着有更好的方法。 任何想法?

+0

您可以在** classname.php **的頂部執行'global $ errors;'一次。 –

+0

你可以聲明一個處理全局$ error數組的函數(例如'addError($ str)'),並在你的類中調用它。 – ccKep

回答

2

基本上任何時候你要聲明一個變量global有可能是一個更好的方式去了解你在做什麼的意志你有沒有寫更清晰,更易於維護的代碼?

下面是我堅持處理你遇到的兩個方法。

class Foo { 

    // example 1: exceptions 
    public function newUser1($username) { 
    if($this->userExists($username)) { 
     throw new Exception("User already exists: $username"); 
    } 
    } 

    // example 2: pass-by-reference 
    public function newUser2($username, &$errors) { 
    if($this->userExists($username)) { 
     $errors[] = "User already exists: $username"; 
     return 
    } 
    } 

} 

$inst = new Foo(); 
$errors = array(); 

// example 1: exception handling 
try { 
    $foo->newUser1('Sammitch'); 
} catch (Exception $e) { 
    $errors[] = $e->getMessage(); 
} 

//example 2: pass-by-reference 
$foo->newUser2('Sammitch', $errors); 
if(count($errors) > 1) { 
    // oh noes! 
} 

例外的一個限制是,當你把它停止執行和異常或者進入catch塊或者,如果沒有catch塊,異常堆滿了,直到它變成一個致命的PHP錯誤。

2

我建議你注入你的$errors而不是全球化它。這樣,你就不必追查那裏它被設置/名爲/ etc

class Test { 
    public function __construct(Array $errors) { 
     $this->errors = $errors; 
    } 
} 

$test = new Test($errors); 
+0

注入很棒,但數據不會回來!數組不是對象,不會作爲參考傳遞。 – Sven

+0

@確定他們有。 '$ test-> errors'或'$ test-> getErrors()'等。 – Sammitch