私有的类属性和类方法
正如之前所注释,PHP 5使得将类属性和方法标记为私有是可能的,这就意味着它们不能在类定义之外被操作或者察看。这点对于保护类的内部工作避免被对象实例操作是有帮助的。考虑下面的例子,这些例子通过对Bear()类增加一个新的私有变量$_lastUnitsConsumed而对此进行了解释:
<?php // PHP 5 // class definition class Bear { // define properties public $name; public $age; public $weight; private $_lastUnitsConsumed; // constructor public function __construct() { $this->age = 0; $this->weight = 100; $this->_lastUnitsConsumed = 0; } // define methods public function eat($units) { echo $this->name." is eating ".$units." units of food... "; $this->weight += $units; $this->_lastUnitsConsumed = $units; } public function getLastMeal() { echo "Units consumed in last meal were ".$this->_lastUnitsConsumed." "; } } ?>
现在,既然$_lastUnitsConsumed变量被声明为私有,那么从对象实例对它进行修改的任意企图都会失败,下面是一个例子:
<?php $bob = new Bear; $bob->name = "Bobby Bear"; $bob->eat(100); $bob->eat(200); echo $bob->getLastMeal(); // the next line will generate a fatal error $bob->_lastUnitsConsumed = 1000; ?>
类方法也可以类似的方式被标记为私有,你自己可以试验一下然后看看结果。