2011-12-05 26 views
1

我知道__isset()是爲一個不存在的屬性。但是我想要一個存在的屬性爲null。 默認情況下,它可能是好的:PHP創建一個訪問的對象時,它的空(如__isset())

class myClass 
{ 
public function __isset($name) 
{ 
    // create an object; 
} 
} 

$a = new myClass(); 
$a->mails->get(); 
$a->users->login(); 

但郵件,用戶對象是無處聲明。因此,這可能是解決方案,但它會導致一個扭曲的類,它反映了在UML圖上壞了,等真正的解決方案可能是:

class myClass 
{ 
public $users = null; 
public $mails = null; 
public function __isset($name) 
{ 
    // create an object BUT IT WONT TRIGGER! 
} 
} 

$a = new myClass(); 
$a->mails->get(); // <- fail! 
$a->users->login(); 

只是因爲用戶,郵件聲明。但它現在反映了良好的結構!辛格爾頓可能已經很好,但我不想要它。當訪問的內容爲空時,是否有辦法觸發某些內容?

回答

1

[編輯]

如果有可能使性能private然後通過function訪問它們也許你可以做一些事情:

public function get_Property($property_name) { 
    if (!isset($this->{$property_name})) { 
     echo "\n Property : '$property_name' cannot be accessed because it is not set or is null \n"; 
     // or create your object here then return it; 
    else { 
     return $this->{$property_name}; 
    } 
} 
+0

ok,但CheckCredentials()在訪問一個null屬性時不會觸發 –

+1

我修改了我的帖子,看看是否可以接受.. – Nonym

1

我想推薦不要打破封裝,並使用getters和setters而不是直接字段尋址。此外,它會根據定義解決您的問題。

1

嗯,也許說明明顯且撇開各種原因您目前的執行方式無法正常工作,您爲什麼不這樣做:

public function getMails() 
{ 
    if (!$this->mails) { 
     $this->mails = new ... whatever ...; 
    } 

    return $this->mails; 
} 

如果您需要一些服務來獲取郵件,注入它的構造函數:

private $mailService; 

public function __construct($mailService) 
{ 
    $this->mailService = $mailService; 
} 

public function getMails() 
{ 
    if (!$this->mails) { 
     $this->mails = $this->mailService->magicallyFetchMails(); 
    } 

    return $this->mails; 
} 

不知道爲什麼你想暴露你的對象屬性。

相關問題