PHP 5 Example
In this section we will discuss about PHP 5 example or you can say PHP 5 class example with explanation.
PHP 5 Class and Object Example
<?php class Laptop { public $name; public $roll; function inserdata($a, $b){ $this->name=$a; $this->roll=$b; } public function displayRecord() { echo $this->name; echo $this->roll; echo "
"; } } $obj =new Laptop(); $obj1 =new Laptop(); $obj->inserdata(" Sony ",1); $obj->displayRecord(); $obj1->inserdata(" Ptutorial ",5); $obj1->displayRecord(); ?>
Output
Sony 1 Ptutorial 5
This example maintain the record of the laptops, we are creating the two objects of Laptop class and initializing the value to these objects by invoking the insertdata method on it. For displaying the data of the object call the displayRecord method on it.
Factorial using PHP 5 class and object
<?php class Fact { private $result = 1; private $number; function __construct($num) { $this->number = $num; for($i=2; $i<=$num; $i++) { $this->result *= $i; } } function display() { echo "Factorial of {$this->number} is {$this->result}.
"; } } $factorial = new Fact(4); $factorial->display(); $factorial1 = new Fact(6); $factorial1->display(); ?>
Output
Factorial of 4 is 24. Factorial of 6 is 720.
This example calculate the factorial of the given number, explanation is same as above php 5 example except we are using constructor in the place of method.