Thursday, July 10, 2014

Simple OOPs example program using PHP

Class Page: Books.php
<?php
class Books // Class name.
{
var $title='5'; // Class variables.
var $price=45;

function __construct() // Constructor.
{
$this->price=100; // Define books's default price is 100.
}

function setTitle($title) // Set title for book.
{
$this->title=$title;
}
function getTitle() // Get tiitle of book.
{
return $this->title;
}

function setPrice($price) // Set price for book.
{
$this->price=$price;
}
function getPrice() // Get price of book.
{
return $this->price;
}
}
?>

Main Page: index.php
<?php
include 'Books.php'; // Include class file.

$tamil=new Books(); // Creating object.
$tamil->setTitle('Tamil Text Book'); // Set tittle.
$tamil->setPrice(150); // Set price.

$english=new Books();
$english->setTitle('Spoken English');
$english->setPrice(180);

$environment=new Books();
$environment->setTitle('Environmental Science');

echo $tamil->getTitle() . ' : ' . $tamil->getPrice().'<br />'; // Display save title and price.
echo $english->getTitle() . ' : ' . $english->getPrice().'<br />';
echo $environment->getTitle() . ' : ' . $environment->getPrice().'<br />';
?>

Output:
Tamil Text Book : 150
Spoken English : 180
Environmental Science : 100

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...