A single PHP program can contain any number of classes. They are the user-defined types that consist of objects and is the combination of data and functions. These two are called as members of the class.
Class is the blue-print
of an object.It does not define any data directly but the class represents two important functions of an object such as:
A class is represented with a keyword class
The identifier used specifies the class name. Class body is given in {}. The class definition ends with a semicolon ;.
Below is the syntax to represent an Object.An object of the class can be created by using new
keyword.
Multiple objects of same class can also be created in which each object is different from other.
[php]
$objClass1 = new myClass();
$objClass2 = new myClass();[/php]
Object Operator : To access object property, object operator is used.This is denoted with ->.
//Creating various object of class interestCalculator to calculate interest on various amount
$calculator1 = new InterestCalculator();
$calculator2 = new InterestCalculator();
//Accessing object properties
$calculator1->rate = 3;
$calculator1->duration =2;
$calculator1->capital = 300;
$calculator2->rate = 3.2;
$calculator2->duration =3;
$calculator2->capital = 400;
$interest1 = $calculator1->calculateInterest();
$interest2 = $calculator2->calculateInterest();
echo "Your interest on capital $calculator1->capital with rate $calculator1->rate for duration $calculator1->duration is $interest1 <br/> ";
echo "Your interest on capital $calculator2->capital with rate $calculator2->rate for duration $calculator2->duration is $interest2 <br/> ";
?>
</body>
</html>
[/php]
Output:
[php]Your interest on capital 300 with rate 3 for duration 2 is 18
Your interest on capital 400 with rate 3.2 for duration 3 is 38.4 [/php]
function __construct
(it has two underscores).
[php]
<?php
class interestCalculator
{
public $rate;
public $duration;
public $capital;
//Constructor of the class
public function __construct($rate , $duration)
{
$this->rate = $rate;
$this->duration = $duration;
}
}
$objCls = new interestCalculator(3.2 , 7) //passing value of $rate and $duration
?>
[/php]
[php]
<?php
class person {
var $name;
public $height;
protected $social_insurance;
private $pinn_number;
function __construct($persons_name) {
$this->name = $persons_name;
}
function set_name($new_name) {
$this->name = $new_name;
}
function get_name() {
return $this->name;
}
}
?>
[/php]