Professional Documents
Culture Documents
CONCEPT OF OOP
INTRODUCTION
Object-oriented programming is an approach to programming where objects and classes are
used. Now-a-days Java and C++ are mostly used for object-oriented programming. There
was limited scope of object-oriented programming in PHP 4, but in PHP 5, the object model
was rewritten for better performance and more features. Now PHP 5 has a full object
model.
Object
The fundamental idea behind an object-oriented language is to enclose a bundle of variables
and functions into a single unit and keep both variables and functions safe from outside
interference and misuse. Such a unit is called object which acts on data. The mechanism
that binds together data and functions are called encapsulation. This feature makes it easy
to reuse code in various projects. The functions declared in an object provides the way to
access the data. The functions of an object are called methods and all the methods of an
object have access to variables called properties.
The following picture shows the components of an object.
Member Data
Member Function
Class
In object-oriented programming, a class is a construct or prototype from which objects are
created. A class defines constituent members which enable class instances to have state and
behavior. Data field members enable a class object to maintain state and methods enable a
class object's behavior. The following picture shows the components of a class.
Object
Member Data 1
Class
Member Data 2
Member Data 1
Member Data 2
• The class definition starts with the keyword class followed by a class name, then
followed by a set of curly braces ({}) which enclose constants, variables (called
"properties"), and functions (called "methods") belonging to the class.
• A valid class name (excluding the reserved words) starts with a letter or underscore,
followed by any number of letters, numbers, or underscores.
• Class names usually begin with an uppercase letter to distinguish them from other
identifiers.
Example:
<?php
classMyclass
{
// Add property statements here
// Add the methods here
}
?>
In the following example keyword new is used to instantiate an object. Here $myobj
represents an object of the class Myclass.
Example:
<?php
$myobj=newMyClass;
?>
Properties
• Class member variables are called properties. Sometimes they are referred as attributes
or fields.
• The properties hold specific data and related with the class in which it has been defined.
• Declaring a property in a class is an easy task, use one of the keyword public, protected,
or private followed by a normal variable declaration. If declared using var
(compatibility with PHP 4), the property will be defined as public.
o public : The property can be accessed from outside the class, either by the
script or from another class
o private : No access is granted from outside the class, either by the script or
from another class.
o protected : No access is granted from outside the class except a class that’s a
child of the class with the protected property or method.
• nowdocs ( as of PHP 5.3.0) can be used in any static data context, including property
declarations.
Example:
After an object is instantiated, you can access the property of a class using the object and
-> operator. Any member declared with keyword "private" or "protected" cannot be
accessed outside the method of the class.
<?php
classMyclass
{
public$font_size=10;
}
$f=newMyClass;
echo$f->font_size;
?>
Output:
10
Note: There is a common mistake to use more than one dollar sign when accessing
variables. In the above example there will be no $ sign before font_size (echo $f->font_size).
After defining methods we will discuss an example with public, private and protected class
properties.
Setting Methods
• Declaring a method in a class is an easy task, use one of the keyword public,
protected, or private followed by a method name.
o protected : No access is granted from outside the class except a class that’s a
child of the class with the protected property or method.
• A valid method name starts with a letter or underscore, followed by any number of
letters, numbers, or underscores.
• The method body enclosed within a pair of braces which contains codes. The
opening curly brace ( { ) indicates the beginning of the method code and the closing
curly ( } ) brace indicates the termination of the method.
• If the method is not defined by public, protected, or private then default is public.
• Can access properties and methods of the current instance using $this (Format $this-
>property) for non static property.
Example:
After an object is instantiated, you can access the method of a class using the object and -
> operator. In the following example customize_print() method will print a string with a
specific font size and color within a html paragraph element with the help of php echo
statement.
<?php
classMyclass
{
public$font_size="18px";
public$font_color="blue";
public$string_name="Harivandana College";
publicfunctioncustomize_print()
{
echo"<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this-
>string_name."</p>";
}
}
$f=newMyClass;
echo$f->customize_print();
?>
Output:
Harivandana College
Now change the value of font_size, font_color and the string and check what the
method custimize_print() returns.
<?php
classMyclass
{
public$font_size="18px";
public$font_color="blue";
public$string_name="Harivandana College";
publicfunctioncustomize_print()
{
echo"<p style=font-size:".$this->font_size.";color:".$this-
>font_color.";>".$this->string_name."</p>";
}
}
$f=newMyClass;
$f->font_size="20px";
$f->font_color="red";
$f->string_name="Object Oriented Programming";
echo$f->customize_print();
?>
In PHP, the scope resolution operator is also called "double colon" or "double dot twice" in
Hebrew. The double colon (::), is a token which allows access to static, constant, and
overridden properties or methods of a class.
Example:
<?php
Class Book
{
Const NAME = " Let us C";
Const AUTHOR="Yashwant Kanetkar";
}
echo"Name of Book:<br>";
echoBook::NAME;
echo"<br>Name of Author:<br>";
echoBook::AUTHOR;
?>
Output:
Name of Book:
Let us C
Name of Author:
Yashwant Kanetkar
• Constant names are not preceded by a dollar sign ($) like a normal variable
declaration.
• When calling a class constant using the $classname :: constant syntax, the classname
can actually be a variable.
• As of PHP 5.3, you can access a static class constant using a variable reference
(Example: className :: $varConstant).
<?php
classMyClass
{
const constant1 ='PHP Class Constant';
functionPrintConstant()
{
echoself::constant1 ."<br>";
}
}
echoMyClass::constant1 ."<br>";
$classname="MyClass";
echo $classname::constant1 ."<br>";// As of PHP 5.3.0
$class=newMyClass();
$class->PrintConstant();
echo $class::constant1."<br>";// As of PHP 5.3.0
?>
• The constructor is a special built-in method, added with PHP 5, allows developers to
declare for classes.
• The constructor is not required if you don't want to pass any property values or
perform any actions when the object is created.
Example:
<?php
// Define a class
classMyclass
{
// Declaring three private varaibles
private$font_size;
private$font_color;
private$string_value;
// Declarte construct method which accepts three parameters
function__construct($font_size,$font_color,$string_value)
{
$this->font_size=$font_size;
$this->font_color=$font_color;
$this->string_value=$string_value;
}
// Declare a method for customize print
functioncustomize_print()
{
echo"<p style=font-size:".$this->font_size.";color:".$this-
>font_color.";>".$this->string_value."</p>";
}
}
// Create a new object and passes three parameters
$f=newMyClass('20px','red','Object Oriented Programming');
// Call the method to display the string
echo$f->customize_print();
?>
• A destructor function cleans up any resources allocated to an object after the object
is destroyed.
function __destruct
{
/* Class initialization code */
}
The type of argument1, argument2,.......,argumentN are mixed.
PHP: Inheritance
• Allows subclasses to share the methods and properties (which are public or
protected) of its superclass.
Base Class
Base Class
Example:
In the following example subclass, 'Mysubclass' inherits all the protected properties and
public method from 'Myclass' class. In addition, we add a text-decoration attribute within
echo statement in the subclass 'Mysubclass'.
<?php
// Define a class
classMyclass
{
// Declaring three protected varaibles protected $font_size;
protected$font_color;
protected$string_value;
// Declarte construct method which accepts three parameters and the method
customize_print()
function__construct($font_size,$font_color,$string_value)
{
$this->font_size=$font_size;
$this->font_color=$font_color;
$this->string_value=$string_value;
$this->customize_print();
}
// Declare a method for customize print
publicfunctioncustomize_print()
{
echo"<p style=font-size:".$this->font_size.";color:".$this-
>font_color.";>".$this->string_value."</p>";
}
}
// Define a subclass
classMysubclassextendsMyclass
{
// Call the method customize print() and add the text decoration attribute within
echo statement
publicfunctioncustomize_print()
{
echo"<p style=font-size:".$this->font_size.";color:".$this->font_color.";text-
decoration:underline;>".$this->string_value."</p>";
}
}
// Create objects and passes parameters
$p=newMyclass('20px','red','Object Oriented Programming');
$s=newMysubclass('15px','green','Object Oriented Programming');
?>
Example :
This example attempts to load the classes MyClass1 and MyClass2 from the files
MyClass1.php and MyClass2.php respectively.
Index.php
<?php
Function __autoload($className)
{
Include_once(“$className.php”);
}
$obj1= new MyClass1();
$obj2= new MyClass2();
?>
Abstract Classes
Abstract classes and methods are when the parent class has a named method, but need its child
class(es) to fill out the tasks.
An abstract class is a class that contains at least one abstract method. An abstract method is a
method that is declared, but not implemented in the code.
<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
}
?>
Interfaces make it easy to use a variety of different classes in the same way. When one or more
classes use the same interface, it is referred to as "polymorphism".
<?php
interface InterfaceName {
public function someMethod1();
public function someMethod2($name, $color);
}
?>
Interface are similar to abstract classes. The difference between interfaces and abstract classes
are:
A class that implements an interface must implement all of the interface's methods.
<?php
interface Animal {
public function makeSound();
}
Anonymous Class
At the most fundamental level an Anonymous Class is simply a class definition without a name. It is
defined just like any other class. In truth, they do have internally generated names so we do not
need to provide the names.
<?php
$obj= new class(){
public function show(){
echo "this is anonymous funciton example";
}
};
$obj->show();
?>
Object Iteration
From PHP 5 onwards, it is possible to iterate through list of all visible items of an object.
Iteration can be performed using foreach loop as well as iterator interface. There is
also IteratorAggregate interface in PHP, that can be used for this purpose
<?php
class myclass{
private $var;
protected $var1;
public $x, $y, $z;
public function __construct(){
$this->var="private variable";
$this->var1=TRUE;
$this->x=100;
$this->y=200;
$this->z=300;
}
public function iterate(){
foreach ($this as $key => $value) {
print "$key => $value\n";
}
}
}
$obj = new myclass();
foreach($obj as $key => $value) {
print "$key => $value\n";
}
echo "\n";
$obj->iterate();
?>
In the below example, we are copying objects by using PHP clone keyword. PHP’s
clone method does a shallow copy and so, any changes made in the cloned object
will not affect original object.
__clone is a magic method in PHP. Magic methods are predefined in PHP and
starts with “__” (double underscore). They are executed in response to some
events in PHP.
<?php
//Creating instance of Animals class
$objAnimals =newAnimals();
//Assigning values
$objAnimals->name ="Lion";
$objAnimals->category ="Wild Animal";
//Cloning the original object
$objCloned = clone $objAnimals;
$objCloned->name ="Elephant";
$objCloned->category ="Wild Animal";
print_r($objAnimals);
print_r($objCloned);
?>
Introduction
PHP has a comparison operator == using which a simple comparison of two objects variables
can be performed. It returns true if both belong to same class and values of corresponding
properties are same.
PHP's === operator compares two object variables and returns true if and only if they refer
to same instance of same class
We use following two classes for comparison of objects with these operators
Example
<?php
class test1{
private $x;
private $y;
function __construct($arg1, $arg2){
$this->x=$arg1;
$this->y=$arg2;
}
}
class test2{
private $x;
private $y;
function __construct($arg1, $arg2){
$this->x=$arg1;
$this->y=$arg2;
}
}
?>
Two objects of same class
Example
$a=new test1(10,20);
$b=new test1(10,20);
echo "two objects of same class\n";
echo "using == operator : ";
var_dump($a==$b);
echo "using === operator : ";
var_dump($a===$b);
Output
two objects of same class
using == operator : bool(true)
using === operator : bool(false)
two references of same object
Example
$a=new test1(10,20);
$c=$a;
var_dump($a==$c);
var_dump($a===$c);
Output
two references of same object
using == operator : bool(true)
using === operator : bool(true)
two objects of different classes
Example
$a=new test1(10,20);
$d=new test2(10,20);
echo "two objects of different classes\n";
echo "using == operator : ";
var_dump($a==$d);
echo "using === operator : ";
var_dump($a===$d);
Output
Output shows following result
<?php
class Student {
private $name;
private $email;
The __destruct() method is called a destructor, and it’s called when the object is
destroyed. Generally, it’s also called when the script is stopped or exited. The purpose of
this method is to provide an opportunity to save the object state or any other cleanups you
would want to perform.
<?php
classStudent {
private$name;
private$email;
publicfunction__construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}
publicfunction__destruct()
{
echo'This will be called when the script is shut down...';
// save object state/other clean ups
}
}
$objStudent= newStudent('John', 'john@tutsplus.com');
?>
The __set() magic method is called when you try to set data to inaccessible or non-existent
object properties. The purpose of this method is to set extra object data for which you
haven’t defined object properties explicitly.
<?php
classStudent {
private$data= array();
publicfunction__set($name, $value)
{
$this->data[$name] = $value;
}
}
$objStudent= newStudent();
// __set() called
$objStudent->phone = '0491 570 156';
?>
As you can see in the above example, we’re trying to set the phone property, which is non-
existent. And thus, the __set() method is called. The first argument of the __set() method
is the name of the property which is being accessed, and the second argument is the value
we’re trying to set.
In the case of the __set() method example in the previous section, we discussed how to set
values for non-existent properties. The __get() method is exactly the opposite of it.
The __get() magic method is called when you try to read data from inaccessible or non-
existent object properties. The purpose of this method is to provide values to such
properties.
<?php
classStudent {
private$data= array();
publicfunction__set($name, $value)
{
$this->data[$name] = $value;
}
publicfunction__get($name)
{
If (isset($this->data[$name])) {
return$this->data[$name];
}
}
}
$objStudent= newStudent();
// __set() called
$objStudent->phone = '0491 570 156';
// __get() called
echo$objStudent->phone;
?>
The __toString() magic method allows you to define what you would like to display when
an object of the class is treated like a string. If you use echo or print on your object, and
you haven’t defined the __toString() method, it’ll give an error.
<?php
classStudent {
private$name;
private$email;
publicfunction__construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}
publicfunction__toString()
{
return'Student name: '.$this->name
. '<br>'
. 'Student email: '.$this->email;
}
}
If __get() and __set() methods are called when you’re dealing with non-existent
properties, the __call() method is called when you’re trying to invoke inaccessible
methods, the methods that you haven’t defined in your class.
<?php
classStudent {
publicfunction__call($methodName, $arguments)
{
// $methodName = getStudentDetails
// $arguments = array('1')
}
}
$objStudent= newStudent();
$objStudent->getStudentDetails(1);
?>
As you can see, we’ve called the method getStudentDetails , which is not defined, and thus
the __call() magic method is called. The first argument is the name of the method being
called, and the second argument is an array of arguments that were passed in that method.
The __callStatic() method is very similar to the __call() method; the only exception is that
it’s called when you’re trying to invoke inaccessible methods in a static context. So if you’re
trying to access any static method which is not defined, the __callStatic() function will be
called.
The __isset() magic method is called when you call the isset() method on inaccessible or
non-existent object properties. Let’s see how it works through an example.
<?php
classStudent {
private$data= array();
publicfunction__isset($name)
{
returnisset($this->data[$name]);
}
}
$objStudent= newStudent();
echoisset($objStudent->phone);
?>
In the above example, the phone property is not defined in the class, and thus it’ll call
the __isset() method.
On the other hand, the __unset() is a method called when you call the unset() method on
inaccessible or non-existent object properties.
If you want to duplicate an existing object, you could use the clone keyword to do that. But
after cloning, if you want to modify properties of the cloned object, you can define
the __clone() magic method in your class.
<?php
Class Student_School {
}
classStudent {
private$name;
private$email;
private$object_student_school;
publicfunction__construct()
{
$this->object_student_school = newStudent_School();
}
publicfunction__clone()
{
$this->object_student_school = clone$this->object_student_school;
}
}
$objStudentOne= newStudent();
$objStudentTwo= clone$objStudentOne;
?>
The issue with the above approach is that it makes a shallow copy of the object while
cloning, and thus internal objects of the cloned object will not be cloned.
In the context of the above example, if you hadn’t defined the __clone() method, the
cloned object, $objStudentTwo , would still point to the same Student_School object
referenced by the $objStudentOne object. Thus, by implementing the __clone() method,
we make sure that the Student_School object is cloned along with the main object.
Static Keyword
Declaring class properties or methods as static makes them accessible without needing an
instantiation of the class. A property declared as static cannot be accessed with an
instantiated class object (though a static method can).
Because static methods are callable without an instance of the object created, the pseudo-
variable $this is not available inside the method declared as static.
<?php
class Demo {
public static $colg;
public static function aStaticMethod() {
echo “static method called”;
}
}
Demo::$colg=”harivandana college”;
Demo::aStaticMethod();
?>
Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from overriding a method
by prefixing the definition with final. If the class itself is being defined final then it cannot be
extended.
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
only in the run time. Overriding a property in child class and creating the instance of the
child class, so to get the overridden output, the late static binding concept is used by writing
static keyword before using the property. Whenever a PHP interpreter gets the request to
compile a function. If it sees any static property, then it leaves the property pending for run
time and the property gets its value during runtime from the function it is being called. This
is called late static binding.
This feature of late static binding was introduced in PHP 5.3 and above, previous versions
will show a fatal error.
<?php
class Demo{
public static $name="Harivandana College";
public static function view(){
echo "Demo class Welcome to ".self::$name;
}
public static function viewSecond(){
static::view();
//echo $op." yes its success";
}
}
class DemoNew extends Demo{
public static function view(){
echo "welcome to ".self::$name." - Rajkot";
}
}
class DemoThree extends DemoNew{
public static function view(){
echo "welcome to ".self::$name." - munjka, rajkot";
}
}
Demo::viewSecond();
echo "<br>";
DemoNew::viewSecond();
echo "<br>";
DemoThree::viewSecond();
?>
Type Hinting
o In simple word, type hinting means providing hints to function to only accept the
given data type.
o In technical word we can say that Type Hinting is method by which we can force
function to accept the desired data type.
o In PHP, we can use type hinting for Object, Array and callable data type.
Example 1
<?php
class a
{
public $c= "hello welcome to Harivanda";
}
//create function with class name argument
Function show($name) – built-in datatype
function display(a $a1) - user define data type
{
//call variable
echo $a1->c;
}
display(new a());
?>
Example 2
<?php
class Test1
{
public $var= "welcome to harivandana college -rajkot";
}
//create function with class name argument
function typehint(Test1 $t1)
{
//call variable
echo $t1->var;
}
//call function with call name as a argument
typehint(new Test1());
?>
<?php
class myClass {
public $var;
function __construct() {
$this->var = 1;
}
function inc() {
return ++$this->var;
}
}
$a = new myClass(); //obj create
$b = $a; //obje pass as value ( both object value address are different)
total created address are 2
echo "a = ";
var_dump($a);
echo "<br>b = ";
var_dump($b);
$c = &$a; //obj pass as ref( both object value address are same) total
created address in 1 that main object address
echo "<br>c = ";var_dump($c);
$a = NULL;
echo "<br>a = ";var_dump($a);
echo "<br>b = ";var_dump($b);
echo "<br>c = ";var_dump($c);
echo "<br>b->inc: ".$b->inc();
echo "<br>b->inc: ".$b->inc();
$b = NULL;
echo "<br>b = ";var_dump($b);
?>