Forum Moderators: coopster
I know that if I create an instance of a class I can access its properties and functions with a single -> operator...
$someVar->A->B->C->D->methodOfD();
/**
* Our address book class
*/
class AddressBook implements IAddressBook {
/**
* Get the fullname of the passed user
* @param string $userId A registered user's ID
*/
public function getFullname($userId) {
$fullname = null;
/* Lookup users fullname for user $userId, throw Exception on error, etc. */
return $fullname;
}
public function getEmailAddress($userId) {
$emailAddr = null;
/* Lookup primary email address for user $userId */
return $emailAddr;
}
public function getTelephoneNumber($userId) {
/* Etc. */
}
}
/**
* A class for emailing users (from our address book)
*/
class Emailer {
/**
* Class property holds an instance of our address book
* which is passed into the constructor (when the class is instantiated)
*/
protected $_addressBook = null;
/**
* Default "From" address
* - Override in extended class
*/
protected $_fromAddress = 'noreply@example.com';
/**
* Class constructor
* @param IAddressBook $addressBook An instance (ie. object) of our address book
*/
public function __construct(IAddressBook $addressBook) {
// Assign passed object to our class property
// "this" is a special variable referring to the current class instance
$this->_addressBook = $addressBook;
}
/**
* Send welcome email to user
* @param string $userId A registered user's ID of the user we wish to send the email to
*/
public function sendWelcome($userId) {
// ** MAGIC **
// Lookup details about user in our address book
$userName = $this->_addressBook->getFullname($userId);
$userEmail = $this->_addressBook->getEmailAddress($userId);
$body = <<<EOD
Hi $userName,
Welcome to WebmasterWorld!
EOD;
}
mail($userEmail, 'Welcome to WebmasterWorld', $body, 'From: '.$this->_fromAddress);
}
// Instantiate the AddressBook
$addressBook = new AddressBook();
// Instantiate the Emailer, passing our already instantiated AddressBook to the constructor
$emailer = new Emailer($addressBook);
// Send a welcome email to a user whose ID is...
$emailer->sendWelcome('whitespace');