简体   繁体   中英

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM