繁体   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