03 Understanding Objects in PHP (1)
03 Understanding Objects in PHP (1)
Objects in PHP
Prof. Sachin Ponde
Creating Classes
▪ PHP allows us to create your own function, it also allows
us to group related functions together using a class.
▪ Classes are the fundamental construct behind object-
oriented programming (OOP), a programming paradigm
that involves modeling program behaviour into “objects”
and then using these objects as the basis for our
applications.
Introducing Classes and Objects
▪ Class is a self-contained, independent collection of
variables and functions, which work together to perform
one or more specific tasks.
▪ Variables within a class are called properties; functions are
called methods.
▪ Classes serve as templates for objects, which are specific
instances of a class.
▪ Every object has properties and methods corresponding to
those of its parent class.
▪ Every object instance is completely independent, with its
own properties and methods, and can thus be manipulated
independently of other objects of the same class.
Example
Object
break()
Ford accelerate()
Class turn()
Automobile
(color, make)
Object
break()
break()
accelerate()
Honda accelerate()
turn()
turn()
Defining Class in PHP
<?php
//Class definition
Class Automobile {
//properties
public $color;
public $make;
//methods
public function accelerate()
{
echo ‘Accelerating….’;
}
public function break()
{
echo ‘Slowing down….’;
}
public function turn()
{
echo ‘Turning….’;
}
}
?>
Using Class in PHP
<?php
//instantiate object
$car = new Automobile;
//properties
public $color;
public $make;
public $speed = 55;
//methods
public function accelerate()
{
$this -> $speed += 10;
echo ‘Accelerating….’.$this->$speed.’….’;
}
public function break1()
{
$this -> $speed -= 10;
echo ‘Slowing down to….’.$this->$speed.’….’;
}
public function turn()
{
$this->break1();
echo ‘Turning…’;
$this->accelerate();
}
}
?>
▪ When invoke these functions, can see the effect of changes in
$speed
<?php
//instantiate object
$car = new Automobile;
//invoke methods
//output: ‘Accelerating to 65…’
// ‘Slowing down to 55…’
// ‘Turning…’
// ‘Accelerating to 65…’
$car -> accelerate();
$car -> turn();
?>
References
▪ A Beginner’s Guide – PHP, Vikram Vaswani