Simple class definition in PHP

Here is a simple class definition in PHP

<?php

class Box {

private $_length;
private $_width;
private $_height;

public function Box($length, $width, $height) {
$this->_length = $length;
$this->_width = $width;
$this->_height = $height;
}

public function volume() {
return $this->_length * $this->width * $this->_height;
}

}

//Example of using the class
$myBox = new Box(20,10, 5);
$myVolume = $myBox->volume();
echo($myVolume);

?>

The definitions of each access modifier :

public. Public members can be accessed both from outside an object by using $obj->publicMember and by accessing it from inside the myMethod method via the special $this variable (for example, $this->publicMember). If another class inherits a public member, the same rules apply, and it can be accessed both from outside the derived class’s objects and from within its methods.

protected. Protected members can be accessed only from within an object’s method—for example, $this->protectedMember. If another class inherits a protected member, the same rules apply, and it can be accessed from within the derived object’s methods via the special $this variable.

private. Private members are similar to protected members because they can be accessed only from within an object’s method. However, they are also inaccessible from a derived object’s methods. Because private properties aren’t visible from inheriting classes, two related classes may declare the same private properties. Each class will see its own private copy, which are unrelated.

Leave a Reply