簡體   English   中英

在PHP中,如何在另一個類的靜態變量中引用一個類

[英]In PHP, how to reference a class in another class' static variable

在PHP中使用靜態類/方法時,我不確定如何執行以下操作。 該代碼將不會運行,但是應該使您對我想做什么有所了解。

class Accounts {
   static public $emailer = Site_Emailer;
   static function add( $id ) {
       self::$emailer::send( 'New account created' );
   }
}

然后在單元測試中,我想測試調用此方法將發送一封電子郵件:

function testAccountsAddEmails() {

    Accounts::$email = Mock_Emailer;
    Accounts::add( 1 );

    $this->assertTrue( count( Mock_Emailer::$sent ) === 1 );
}

我遇到的問題是Accounts $emailer的靜態變量不能只保存類,我可以讓它保存類名的字符串,然后使用call_user_func()但這似乎有些混亂。

我希望這可以澄清我遇到的問題,如果需要更多說明,請告訴我!

謝謝

class Accounts {
   static public $emailer = 'Site_Emailer'; // String representation of class name
   static function add( $id ) {
       call_user_func(
           array(self::$emailer, 'send'),
           'New account created' 
       );
   }
}

同樣,在測試用例中將字符串分配給變量時,必須使用字符串:

Accounts::$email = 'Mock_Emailer`; 

但是考慮使用真實對象和依賴注入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM