在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
的静态变量不能只保存Class,我可以让它保存一个类名字符串,然后使用call_user_func()
但这似乎有点凌乱。
我希望澄清我遇到的问题,如果需要更多说明,请告诉我!
由于
答案 0 :(得分:4)
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`;
但考虑使用真实对象和依赖注入。