You are on page 1of 63

PHP

Object Oriented Programming


CLASS, OBJECT AND METHOD
Object-oriented programming is an approach to programming where objects and
classes are used. 
OBJECT
 An entity that has state and behavior is known as an object
 Example. dog, chair, bike, marker, pen, table, car etc.

 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.

If we consider a dog,
 state is - name, breed, color,

 behavior is - barking, running


 If you compare the software object with a real world object, they have very
similar characteristics.
 Software objects also have a state and behavior.

 A software object's state is stored in fields (data members) and

 behavior is shown via methods

 To declare and create an object you use the syntax

object_name = new class_name (arguments);


CLASS
 A class is a group of objects that has common properties.
 It is a template or blueprint from which objects are created. So object is the
instance(result) of a 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
behaviour. Data field members enable a class object to maintain state and methods enable
a class object's behaviour.

A class can contain:


 data member
 method
 constructor
 class and interface
SYNTAX TO DECLARE A CLASS:
class <class_name> Class Names - For all class names the first letter should
{   be in Upper Case. 

    data member;   If several words are used to form a name of the class,


    method;   each inner word's first letter should be in Upper Case.

}  Example:  class MyFirstPhpClass


<?php
class Myclass
{
// Add property statements here
// Add the methods here
}
$myobj = new MyClass;
var_dump($myobj);
?>
Note: Using var_dump() function (display structured information (type and value) about one or more
variables):
Output:
object(Myclass)#1 (0) { }
PHP OOPS CONCEPTS
 Object
 Class

 Inheritance

 Polymorphism

 Abstraction

 Encapsulation
OOPS CONCEPTS
Object
 Any entity that has state and behavior is known as an object. For example:
chair, pen, table, keyboard, bike etc. It can be physical and logical.
Class
 Collection of objects is called class. It is a logical entity.

Inheritance
 When one object acquires all the properties and behaviours of parent
object i.e. known as inheritance. It provides code reusability. It is used to
achieve runtime polymorphism.
OOPS CONCEPTS
Polymorphism
 When one task is performed by different ways i.e. known as
polymorphism. For example: to convince the customer
differently, to draw something e.g. shape or rectangle etc..
OOPS CONCEPTS
Abstraction
 Hiding internal details and showing functionality is known
as abstraction. For example: phone call, we don't know the
internal processing.
Encapsulation
 Binding (or wrapping) code and data together into a single
unit is known as encapsulation. For example: capsule, it is
wrapped with different medicines.
ADVANTAGE OF OOPS OVER PROCEDURE-
ORIENTED PROGRAMMING LANGUAGE
 OOPs makes development and maintenance easier where as in
Procedure-oriented programming language it is not easy to
manage if code grows as project size grows.
 OOPs provides data hiding whereas in Procedure-oriented
programming language a global data can be accessed from
anywhere.
 OOPs provides ability to simulate real-world event much more
effectively. We can provide the solution of real word problem if
we are using the Object-Oriented Programming language.
STATIC
The static keyword in PHP is used for memory management mainly.

We can apply static keyword with variables, methods.

The static keyword belongs to the class than instance of the class (object).

The static can be:


variable (also known as class variable)

method (also known as class method)
If you declare any variable as static, it is known static variable.


The static variable can be used to refer the common property of all objects (that is not
unique for each object)
e.g. company name of employees, college name of students etc.


The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable


It makes your program memory efficient (i.e it saves memory).
THIS KEYWORD

There can be a lot of usage of $this keyword. In php, $this is a reference variable that
refers to the current object.

Here is given the 6 usage of php this keyword.


this keyword can be used to refer current class instance variable.

this() can be used to invoke current class constructor.

this keyword can be used to invoke current class method (implicitly)

this can be passed as an argument in the method call.

this can be passed as argument in the constructor call.

this keyword can also be used to return the current class instance.
SETTING 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.
 public : The property can be accessed from outside the class, either by the
script or from another class
 private : No access is granted from outside the class, either by the script or
from another class.
 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.
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
class Myclass
{ public $font_size =10;
}
$f = new MyClass;
echo $f->font_size;
?>
Output:
10
A SAMPLE OF A CLASS IS GIVEN BELOW:
class Dog •Method Names - All method names should start with a Lower
{ Case letter. 
$breed;
$age; If several words are used to form the name of the method, then
$color; each inner word's first letter should be in Upper Case.
void barking()
{ Example:  public void myMethodName()
}
void hungry()
{
}
void sleeping()
{
}
}
SETTING METHODS
 In PHP, a method is like function (i.e.) used to expose behaviour of an object.
 The functions which are declared in a class are called methods.
 A class method is exactly similar to PHP functions.
 Declaring a method in a class is an easy task, use one of the keyword public, protected, or
private followed by a method name.

 public : The method can be accessed from outside the class.


 private : No access is granted from outside the class.
 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.
 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.

Advantage of Method
 Code Reusability
 Code Optimization
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 class Myclass
{
public $font_size ="18px";
public $font_color = "blue";
public $string_name = “SRM";
public function customize_print()
{
echo "<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_name."</p>";
}
}
$f = new MyClass;
echo $f->customize_print();
?>
 Now change the value of font_size, font_color and the string and check what the
method custimize_print() returns.
<?php
class Myclass
{
public $font_size ="18px";
public $font_color = "blue";
public $string_name = “SRM";
public function customize_print()
{
echo "<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_name."</
p>";
}}
$f = new MyClass;
$f->font_size = "20px";
$f->font_color = "red";
$f->string_name = "Object Oriented Programming";
echo $f->customize_print();
?>
Output: Object Oriented Programming
PHP: SCOPE RESOLUTION OPERATOR (::)
 In PHP, the scope resolution operator is also called Paamayim Nekudotayim
which means "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.
PHP: Class Constants

 A special entity that remains fixed on an individual class basis.


 Constant names are not preceded by a dollar sign ($) like a normal

variable declaration.
 Interfaces may also include constants.

 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).


DEFINE AND USING A CONSTANT
<?php
class MyClass
{
const constant1 = 'PHP Class Constant';
function PrintConstant()
{
echo self::constant1 . "<br>";
}
}
echo MyClass::constant1 . "<br>";
$classname = "MyClass";
echo $classname::constant1 . "<br>"; // As of PHP 5.3.0
$class = new MyClass();
$class->PrintConstant();
echo $class::constant1."<br>"; // As of PHP 5.3.0
?>
UNDERSTANDING PUBLIC, PRIVATE, PROTECTED
PROPERTIES

 Properties can be public, private or protected.


 Public means that properties can be accessed everywhere,

 private means properties can be accessed by the class that defines the
member and
 protected means properties can be accessed only within the class itself and
by inherited and parent classes.
EXAMPLE:
<?php
// Define a class
class Myclass
{
// Declare $font_size as Public property
public $font_size ="18px";
// Declare $font_color as Private property
private $font_color = "blue";
// Declare $string_name as Protected property
protected $string_name = “SRM";
// Declare a method to print properties value. This is public.
function property_print()
{
echo $this->font_size;
echo $this->font_color; e
cho $this->string_name;
}}
$obj = new MyClass;
echo $obj->font_size;//Display 18px
echo $obj->font_color; //Fatal error: Cannot access private property Myclass::$font_color in F:\wamp\..
echo $obj->string_name; //Fatal error: Cannot access protected property Myclass::$string_name in F:\wamp\..
$obj->property_print(); //Display 18pxbluew3resource
?>
UNDERSTANDING PUBLIC, PRIVATE, PROTECTED
METHODS
 Methods can be public, private or protected.
 Public means that methods can be accessed everywhere,

 private means methods can be accessed by the class that defines the member
and
 protected means methods can be accessed only within the class itself and by
inherited and parent classes.
<?php
// Define a class
class Myclass
{
// Declare a public method
public function my_public_method()
{
echo "This is a Public method";
}
private function my_private_method()
{
echo "This is a Private method";
}
protected function my_protected_method()
{
echo "This is a Protected method";
} // This is public
function test()
{
$this->my_public_method();
$this->my_private_method();
$this->my_protected_method();
}}
$obj = new MyClass;
$obj->my_public_method(); //Display This is a Public method
$obj->my_private_method();//Fatal error: Call to private method Myclass::my_private_method() from context '' in
F:\wamp\www..
$obj>my_protected_method();//Fatal error: Call to undefined function my_protected_method() in F:\wamp\www..
obj->test(); //Display This is a Public methodThis is a Private methodThis is a Protected method
?>

Note: 
PHP uses inheritance in it's object model and when you extend a class, the subclass inherits all of the public and
protected methods from the parent class. When we will discuss the inheritance, you will get more information
about protected properties and methods.
PHP CONSTRUCTOR METHODS
 Constructor in PHP is a special type of method that is used to initialize the object.
 PHP constructor is invoked at the time of object creation.
 It constructs the values i.e. provides data for the object that is why it is known as
constructor.
 The constructor is a special built-in method, added with PHP 5, allows developers to
declare for classes.
 Constructors allow to initializing object properties ( i.e. the values of properties)
when an object is created.
 Classes which have a constructor method execute automatically when an object is
created.
 The 'construct' method starts with two underscores (__).
 The constructor is not required if you don't want to pass any property values or
perform any actions when the object is created.
 PHP only ever calls one constructor.
CONSTRUCTOR
Rules for creating PHP constructor
 There are basically two rules defined for the constructor.
 Constructor name must be same as its class name or __construct keyword
Types of PHP constructors
 There are two types of constructors:
 Defaultconstructor (no-arg constructor)
 Parameterized constructor

The general syntax for constructor declaration follows :


function __construct([argument1, argument2, ..., argumentN])
{
/* Class initialization code */
}
The type of argument1, argument2,.......,argumentN are mixed.
EXAMPLE:
<?php
// Define a class
class Myclass
{
// 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
function customize_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 = new MyClass('20px','red','Object Oriented Programming');
// Call the method to display the string
echo $f->customize_print();
?>
Output:Object Oriented Programming
CONSTRUCTOR OVERLOADING
 Constructor overloading is a technique in PHP in which a class can have any
number of constructors that differ in parameter lists.
INHERITANCE
 Inheritance in Real World:
Taking some properties from the parents.
 Inheritance

 Inheritance is a mechanism in which one object acquires all the properties and
behaviors of parent object.

 When you inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.

 Inheritance represents the IS-A relationship, also known as parent-child relationship.

 The main purpose of inheritance is Code Reusability.


Why use Inheritance

 For Method Overriding


 For Code Reusability.
Syntax of Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from
an existing class.

In the terminology of php, a class that is inherited is called a super class. The
new class is called a subclass.
 Understanding the simple example of inheritance

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship
between two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
TYPES OF INHERITANCE

Note: Multiple inheritance is not supported in through class.


SINGLE INHERITANCE

Base Class

Derived Class
MULTILEVEL INHERITANCE

 When a derived class is derived from a base class which itself is a derived class
then that type of inheritance is called multilevel inheritance

Base Class

Derived Class

Derived-derived
Class
HIERARCHICAL INHERITANCE

 When more than one derived class is derived from a base class then that type of
inheritance is called hierarchical inheritance

Base Class

Derived Class Derived Class


MULTIPLE INHERITANCE

Base Class 1 Base Class 2

• php does not implement multiple


inheritance directly

• multiple inheritance is supported through


Derived Class interface only
HYBRID INHERITANCE
 When two or more types of inheritance are combined together then it forms
the hybrid inheritance.

Class A

• php does not implement Hybrid inheritance


directly

• Hybrid inheritance is supported through Class B Class B


interface only if it has multiple inheritance,
otherwise this can be done by classes

Class C
METHOD OVERRIDING
 If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding .
 In other words, If subclass provides the specific implementation of the method
that has been provided by one of its parent class, it is known as method
overriding.

Usage of Method Overriding

 Method overriding is used to provide specific implementation of a method that is


already provided by its super class.
Rules for Method Overriding

method must have same name as in the parent class


method must have same parameter as in the parent class.

must be IS-A relationship (inheritance).


FINAL KEYWORD

The final keyword is used to restrict the user. The final keyword can be used in many
context.

Final can be:


variable
method
class
FINAL VARIABLE

If you make any variable as final, you cannot change the value of final variable(It will be constant.
FINAL METHOD

If you make any method as final, you cannot override it
FINAL CLASS
If you make any class as final, you cannot extend it.
POLYMORPHISM
 Polymorphism is a concept by which we can perform a single action by different
ways.

 Polymorphism is derived from 2 greek words: poly and morphs.

The word "poly" means many and "morphs" means forms.

So polymorphism means many forms.


ABSTRACT CLASS, INTERFACE
Abstraction
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

Another way, it shows only important things to the user and hides the internal
details.

For example : sending sms, you just type the text and send the message. You don't
know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction

There are two ways to achieve abstraction

 Abstract class (0 to 100%)


 Interface (100%)
Abstract class
A class that is declared as abstract is known as abstract class.

It
needs to be extended and its method implemented. It cannot be instantiated.
Example:

abstract class A
{

Abstract method
 A method that is declared as abstract and does not have implementation is known as
abstract method.

Example:

abstract function printStatus();
POINTS TO REMEMBER ABOUT ABSTRACT
CLASSES AND METHODS
 Abstract classes cannot be instantiated (cannot create the object).

 If there is any abstract method in a class, that class must be abstract.

 If you are extending any abstract class that have abstract method, you must either
provide the implementation of the method or make this class abstract.
INTERFACE
 An interface is a blueprint of a class.
 It has static constants and abstract methods only.

 There can be only abstract methods in the interface not method body.

 It is used to achieve fully abstraction

 Interface also represents IS-A relationship


WHY USE PHP INTERFACE?
There are mainly three reasons to use interface. They are given below.

 It is used to achieve fully abstraction.


 It can be used to achieve the standard declaration of function which are to be
implemented by classes.
 It can be used to achieve loose coupling.
Syntax:
interface interface_name
{
function function_name();
function function_name();
}
UNDERSTANDING RELATIONSHIP BETWEEN CLASSES
AND INTERFACES
 A class extends another class, an interface extends another interface but a class
implements an interface.

You might also like