![](/img/trans.png)
[英]php initialize a class static variable with another static variable of another class
[英]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.