PDA

View Full Version : OOP in PHP Part 2.5 - Encapsulation (Private)



Moonbat
07-27-2008, 03:56 PM
As promised, we will cover private methods. If you haven't read part one and two, do so now.

Now, take this code.


<?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>";

?>

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:


function newGiveDetails($thetype, $theflavor, $thecolor) {
$this->giveDetails($thetype, $theflavor, $thecolor);
}

Remember, all methods are public unless explicitly declared otherwise. Step #2 is very easy. Let's see the final code:


<?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>";

?>

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