Starting with PHP 5, you can define a public __get() function that
is called automatically whenever you try to call a method or read a member that isn??™t defined in the class. Take, for
example, this code snippet:
$card = new SecureCard();
$encrypted = $card->EncryptedData;
Because there??™s no member named EncryptedData in the SecureCard class, the __get() function is called.
In __get(), you can check which property is accessed, and you can include code that returns the value for that
property. This technique is particularly useful when you want to define ???virtual??? members of the class whose values
need to be calculated on the spot as an alternative to using get functions such as GetEncryptedData().
In our case, the __get() function handles eight ???virtual??? members. The first is EncryptedData, whose value is
returned only if $_mIsEncrypted is true:
public function __get($name)
{
if ($name == 'EncryptedData')
{
if ($this->_mIsEncrypted)
return $this->_mEncryptedData;
CHAPTER 16 ?– MANAGING CUSTOMER DETAILS 498
else
throw new Exception('Data not encrypted');
}
Then there??™s CardNumberX, which needs to return a version of the card number where all digits are obfuscated
(replaced with X) except the last four. This is handy when showing a user existing details and is becoming standard
practice because it lets customers know what card they have stored without exposing the details to prying
eyes:
elseif ($name == 'CardNumberX')
{
if ($this->_mIsDecrypted)
return 'XXXX-XXXX-XXXX-' .
Pages:
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620