Reputation: 228
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
Upvotes: 0
Views: 379
Reputation: 29462
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.
Upvotes: 4