OOP in PHP Part 2.5 - Encapsulation (Private)
As promised, we will cover private methods. If you haven't read part one and two, do so now.
Now, take this code.
[PHP]<?php
class Cheese {
var $type;
var $flavor;
var $color;
function __construct($atype, $aflavor, $acolor) {
$this->type = $atype;
$this->flavor = $aflavor;
$this->color = $acolor;
}
private function giveDetails ($thetype, $theflavor, $thecolor) {
$this->type = $thetype;
$this->flavor = $theflavor;
$this->color = $thecolor;
}
function showType() {
return $this->type;
}
function showColor() {
return $this->color;
}
function showFlavor() {
return $this->flavor;
}
function __destruct() {
echo "Cheese has been eaten";
}
}
class MoreCheese extends Cheese {
var $cost;
function giveCost($f) {
$this->cost = $f;
}
function showCost() {
return $this->cost;
}
}
$zargento = new MoreCheese("Cheddar", "Good", "Yellow");
$zargento->GiveDetails("Gorgonzola", "Awful", "Green and white");
echo $zargento->showType();
echo "<br>";
echo $zargento->showFlavor();
echo "<br>";
echo $zargento->showColor();
echo "<br>";
?>[/PHP]
We get a fatal error. We need to do the following to use the private giveDetails() function:
*. Make a public function in base class Cheese to access the private function
2. Change $zargento from MoreCheese to Cheese
Step #* is done with a simple function, but instead of using 'parent::' like we did for protected methods, we will use '$this'. Here is what we get:
[PHP] function newGiveDetails($thetype, $theflavor, $thecolor) {
$this->giveDetails($thetype, $theflavor, $thecolor);
}[/PHP]
Remember, all methods are public unless explicitly declared otherwise. Step #2 is very easy. Let's see the final code:
[PHP]<?php
class Cheese {
var $type;
var $flavor;
var $color;
function __construct($atype, $aflavor, $acolor) {
$this->type = $atype;
$this->flavor = $aflavor;
$this->color = $acolor;
}
private function giveDetails ($thetype, $theflavor, $thecolor) {
$this->type = $thetype;
$this->flavor = $theflavor;
$this->color = $thecolor;
}
function newGiveDetails($thetype, $theflavor, $thecolor) {
$this->giveDetails($thetype, $theflavor, $thecolor);
}
function showType() {
return $this->type;
}
function showColor() {
return $this->color;
}
function showFlavor() {
return $this->flavor;
}
function __destruct() {
echo "Cheese has been eaten";
}
}
class MoreCheese extends Cheese {
var $cost;
function giveCost($f) {
$this->cost = $f;
}
function showCost() {
return $this->cost;
}
}
$zargento = new Cheese("Cheddar", "Good", "Yellow");
$zargento->newGiveDetails("Gorgonzola", "Awful", "Green and white");
echo $zargento->showType();
echo "<br>";
echo $zargento->showFlavor();
echo "<br>";
echo $zargento->showColor();
echo "<br>";
?>[/PHP]
The code works perfectly :D
As you can see, encapsulation provides a way to make sure that classes and subclasses have access only to what they need.
Thanks for reading, and I hope you learn something!
~Moonbat