Hide value with private access modifier in PHP
Description
The following code shows how to hide value with private access modifier.
Example
<?php/*from w ww . j a v a 2 s .c o m*/
class Car {
public $color;
public $manufacturer;
public $model;
private $_speed = 0;
public function accelerate() {
if ( $this->_speed >= 100 ) return false;
$this->_speed += 10;
return true;
}
public function brake() {
if ( $this->_speed <= 0 ) return false;
$this->_speed -= 10;
return true;
}
public function getSpeed() {
return $this->_speed;
}
}
$myCar = new Car();
$myCar->color = "red";
$myCar->manufacturer = "Volkswagen";
$myCar->model = "Beetle";
echo "<p>I'm driving a $myCar->color $myCar->manufacturer $myCar->model.</p>";
while ( $myCar->accelerate() ) {
echo "Current speed: " . $myCar->getSpeed() . " mph<br />";
}
while ( $myCar->brake() ) {
echo "Current speed: " . $myCar->getSpeed() . " mph<br />";
}
?>
The code above generates the following result.