0% found this document useful (0 votes)
37 views7 pages

Lab 8

The document discusses object-oriented programming in PHP. It defines what objects and classes are, how to create objects from classes, and how to use properties and methods. It also covers inheritance and constructors.

Uploaded by

hassan IQ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views7 pages

Lab 8

The document discusses object-oriented programming in PHP. It defines what objects and classes are, how to create objects from classes, and how to use properties and methods. It also covers inheritance and constructors.

Uploaded by

hassan IQ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Experiment No.

(8) PHP: part 3


Object oriented
introduction
An object is an enclosed bundle of variables and functions forged from a special template called a class.
Objects hide a lot of their inner workings away from the code that uses them, providing instead easy interfaces
through which you can send them orders and they can return information. These interfaces are special
functions called methods. All the methods of an object have access to special variables called properties.

By defining a class, you lay down a set of characteristics. By creating objects of that type, you create entities
that share these characteristics but might initialize them as different values. You might create an automobile
class, for example. This class would have a color characteristic. All automobile objects would share the
characteristic of color, but some would initialize it to "blue," others to "green," and so on.

Perhaps the greatest benefit of object-oriented code is its reusability. Because the classes used to create objects
are self-enclosed, they can be easily pulled from one project and used in another. Additionally, it is possible to
create child classes that inherit and override the characteristics of their parents. This technique can allow you to
create progressively more complex and specialized objects that can draw on base functionality while adding
more of their own.

Creating an Object

To create an object, you must first design the template from which it can be instantiated. This template is
known as a class, and in PHP, you must declare it with the class keyword:

class Item {
// a very minimal class
}

The Item class is the basis from which you can instantiate any number of Item objects. To create an instance
of an object, you must use the new statement:

$obj1 = new Item();


$obj2 = new Item();
print "\$obj1 is an ".gettype($obj1)."<br />";
print "\$obj2 is an ".gettype($obj2)."<br />";

You can test that $obj1 and $obj2 contain objects with PHP's gettype() function. gettype() accepts any
variable and returns a string that should tell you what you are dealing with. In a loosely typed language like
PHP, gettype() is useful when checking arguments sent to functions. In the previous code fragment,
gettype() returns the string "object", which is then written to the browser.

1|Page
 Objects have access to special variables called properties. You can declare them anywhere within the
body of your class, but for the sake of clarity, you should define them at the top.

Ex:
class Item {
var $name = "item";
}

$obj1 = new Item();


$obj2 = new Item();
$obj1->name = "widget 5442";
print "$obj1->name<br />";
print "$obj2->name<br />";

// prints:
// widget 5442
// item

Notice that we declared our variable with the var keyword. In PHP 4, this was the only way to declare a
property. in PHP 5 gives us a different way to declare our properties. In place of the var keyword, we could
use one of three new keywords (public, private, protected) and this concept of classes known as visibility:

Public properties can be accessed by any code, whether that code is inside or outside the class. If a property is
declared public, its value can be read or changed from anywhere in your script.

Private properties of a class can be accessed only by code inside the class. So if you create a property that ’ s
declared private, only methods inside the same class can access its contents.

Protected class properties are a bit like private properties in that they can ’ t be accessed by code outside the
class, but there ’ s one subtle difference: any class that inherits from the class can also access the properties.

 A method is a function defined within a class. Every object instantiated from the class has the method's
functionality.
<?php
class Item {
var $name = "item";
function getName() {
return "item";
}
}
$item = new Item ();
print $item->getName ();
?>

A class uses the special variable $this to refer to the currently instantiated object. You can think of it as
a personal pronoun. Although you refer to an object by the handle you have assigned it to ($item, for
example), an object must refer to itself by means of the $this variable. Combining the $this
pseudovariable and ->, you can access any property or method in a class from within the class itself.

2|Page
EX:
<?php
class Item {
var $name = "item";
function getName () {
return $this->name;
}
}
$item = new Item ();
$item->name = "widget 5442";
print $item->getName ();
// outputs "widget 5442"
?>
EX:
<?php
class Account {
private $_totalBalance = 0;
public function makeDeposit( $amount ) {
$this- > totalBalance += $amount; }
public function makeWithdrawal( $amount ) {
if ( $amount < $this- > totalBalance ) { $this- > totalBalance -= $amount;
} else {
print( “Insufficient funds < br / > ” ); }}
public function getTotalBalance() { return $this- > totalBalance; } }
$a = new Account;
$a- > makeDeposit( 500 );
$a- > makeWithdrawal( 100 );
echo $a- > getTotalBalance() . “ < br / > ”; // Displays “400”;
$a- > makeWithdrawal( 1000 ); // Displays “Insufficient funds”
?>

EX:
class Rectangle {
public $width = 0;
public $height = 0;
function set_size($w = 0, $h = 0) {
this->width = $w;
$this->height = $h; }
function get_area() {
return ($this->width *$this->height);
}

function get_perimeter() {
return ( ($this->width +$this->height) * 2 );
}
3|Page
function is_square() {
if ($this->width == $this->height) {
return true; // Square
} else {
return false; // Not a square
} }}
?>
_______________________________________________________________________________

<?php require_once (‘Rectangle.php’);


$width = 42;
$height = 7;
echo “<h3>With a width of $width and a height of $height...</h3>”;
$r = new Rectangle();
$r->set_size($width, $height);
echo ‘<p>The area of the rectangle is ‘ . $r->get_area() . ‘</p>’;
echo ‘<p>The perimeter of the rectangle is ‘ . $r->get_perimeter() . ‘</p>’;
echo ‘<p>This rectangle is ‘;
if ($r->is_square()) {
echo ‘also’;
} else {
echo ‘not’;}
echo ‘ a square.</p>’;
unset($r); ?>

Constructors

Constructors are functions in a class that are automatically called when you create a new instance of a class
with new. A function becomes a constructor, when it has the same name as the class. for Writing function
then writes double underscore __ and then write name constructor. See the example below:

function __constructor()
{
}
class Customer {
private $first_name;
private $last_name;
private $outstanding_amount;

public function __construct($first_name, $last_name, $outstanding_amount) {


$this->setData($first_name, $last_name, $outstanding_amount);
}

public function setData($first_name, $last_name, $outstanding_amount) {


$this->first_name = $first_name;
$this->last_name = $last_name;
4|Page
$this->outstanding_amount = $outstanding_amount;
}

public function printData() {


echo "Name : " . $first_name . " " . $this->last_name . "\n";
echo "Outstanding Amount : " . $this->outstanding_amount . "\n";
}

$c1 = new Customer("Sunil","Bhatia",0);

Inheritance
To inherit the properties and methods from another class, use the extends keyword in the class definition,
followed by the name of the base class:
class Person
{
public $name, $address, $age;
}
class Employee extends Person
{
public $position, $salary;
}
The Employee class contains the $position and $salary properties, as well as the $name, $address, and $age
properties inherited from the Person class.
If a derived class has a property or method with the same name as one in its parent class, the property or
method in the derived class takes precedence over the property or method in the parent class. Referencing the
property returns the value of the property on the child, while referencing the method calls the method on the
child. To access an overridden method on an object’s parent class, use the parent::
method() notation:
parent::birthday(); // call parent class's birthday() method
A common mistake is to hardcode the name of the parent class into calls to overridden
methods:
Creature::birthday(); // when Creature is the parent class
This is a mistake because it distributes knowledge of the parent class’s name throughout the derived class.
Using parent:: centralizes the knowledge of the parent class in the extends clause. If a method might be
subclassed and you want to ensure that you’re calling it on the current class, use the self::method() notation:
self::birthday(); // call this class's birthday() method
if ($object instanceof Animal) {
// do something
}
ex:
class Person
{
public $name, $address, $age;
function __construct($name, $address, $age)

5|Page
{
$this->name = $name;
$this->address = $address;
$this->age = $age;
}
}
class Employee extends Person
{
public $position, $salary;
function __construct($name, $address, $age, $position, $salary)
{
parent::__construct($name, $address, $age);
$this->position = $position;
$this->salary = $salary;
}
}
EX:
<?php
class Sites {
private $site;
public $category = 'php-mysql';
public function __construct($site) {
if(is_string($site) && strlen($site)>3) $this->site = $site;
else exit('Invalid value for $site');
}
public function getPag($pag) {
$url = $this->site. '/'. $this->category. '/'. $pag;
return $url;
}
}
?>
_____________________________________________________
<?php
include('class.Sites.php');
class LinkSites extends Sites {
public function getLink($pag) {
echo '<a href="http://'. $this->getPag($pag). '" title="'. $this->category. '">Link</a><br />';
}
}
?>
_______________________
<?php
include('class.LinkSites.php');
$objLink = new LinkSites('http://coursesweb.net');
$objLink->getLink('php-oop-inheritance-class-extends');
$objLink->category = 'ajax';

6|Page
echo $objLink->getPag('xmlhttprequest-object');
?>
EX:

<?php
class Item {
private $name;
function __construct( $name="item", $code=0 ) {
$this->name = $name;
$this->code = $code;
}
function getName() {
return $this->name;
}}
class PriceItem extends Item {
function getName() {
return "(price) ".parent::getName ();
}}
$item = new PriceItem ("widget", 5442);
print $item->getName();
?>

Assignments:

1- Implement the following class hierarchy:

2- What is the difference between protected and private members?

3- Implement a Stack class for stacks of ints. Include a default constructor, a destructor, and the usual stack
operations: push(), pop(), isEmpty(), and isFull(). Use an array implementation

7|Page

You might also like