[英]In PHP, how to reference a class in another class' static variable
When working with static classes / methods in PHP, I am not sure how to do the following. 在PHP中使用静态类/方法时,我不确定如何执行以下操作。 This code will not run, but should give you an idea of what I want to do. 该代码将不会运行,但是应该使您对我想做什么有所了解。
class Accounts { static public $emailer = Site_Emailer; static function add( $id ) { self::$emailer::send( 'New account created' ); } }
Then in a Unit Test, I want to test that calling this method will send an email: 然后在单元测试中,我想测试调用此方法将发送一封电子邮件:
function testAccountsAddEmails() { Accounts::$email = Mock_Emailer; Accounts::add( 1 ); $this->assertTrue( count( Mock_Emailer::$sent ) === 1 ); }
The issue I am running into is the static variable of Accounts $emailer
can not just hold the Class, I could have it hold a string of the class name, then use call_user_func()
but that seems somewhat messy. 我遇到的问题是Accounts $emailer
的静态变量不能只保存类,我可以让它保存类名的字符串,然后使用call_user_func()
但这似乎有些混乱。
I hope that clarifies the issue I am having, let me know if more notes required! 我希望这可以澄清我遇到的问题,如果需要更多说明,请告诉我!
Thanks 谢谢
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'
);
}
}
Similarly, you have to use string while assigning it to variable in your test case: 同样,在测试用例中将字符串分配给变量时,必须使用字符串:
Accounts::$email = 'Mock_Emailer`;
But consider using real objects and dependency injection. 但是考虑使用真实对象和依赖注入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.