在清单 3 中所示的代码版本中,我已经更改了内部实现以使用名称部件的关联数组。比较理想的情况是,我希望拥有错误处理并且更仔细地检查元素是否存在,但是本例的目的在于展示使用我的类的代码无需更改的程度 — 代码并没有察觉到类发生更改。记住采用 OO 习惯的原因是要谨慎封装更改,这样代码将更具有可扩展性并且更容易维护。
清单 3. 使用不同内部实现的另一个示例
<?php
class Person
{
private $personName = array();
public function setPrefix($prefix)
{
$this->personName['prefix'] = $prefix;
}
public function getPrefix()
{
return $this->personName['prefix'];
}
public function setGivenName($gn)
{
$this->personName['givenName'] = $gn;
}
public function getGivenName()
{
return $this->personName['givenName'];
}
/* etc... */
}
/*
* Even though the internal implementation changed, the code here stays exactly
* the same. The change has been encapsulated only to the Person class.
*/
$person = new Person();
$person->setPrefix("Mr.");
$person->setGivenName("John");
echo($person->getPrefix());
echo($person->getGivenName());
?>
class Person
{
private $personName = array();
public function setPrefix($prefix)
{
$this->personName['prefix'] = $prefix;
}
public function getPrefix()
{
return $this->personName['prefix'];
}
public function setGivenName($gn)
{
$this->personName['givenName'] = $gn;
}
public function getGivenName()
{
return $this->personName['givenName'];
}
/* etc... */
}
/*
* Even though the internal implementation changed, the code here stays exactly
* the same. The change has been encapsulated only to the Person class.
*/
$person = new Person();
$person->setPrefix("Mr.");
$person->setGivenName("John");
echo($person->getPrefix());
echo($person->getGivenName());
?>