SlideShare a Scribd company logo
#BURNINGKEYBOARDS
DENIS.RISTIC@PERPETUUM.HR
OBJECT ORIENTED
PROGRAMMING IN PHP
OBJECT ORIENTED PROGRAMMING IN PHP
INTRO TO OOP
▸ Object-oriented programming is a style of coding that
allows developers to group similar tasks into classes.
▸ PHP treats objects in the same way as references or
handles, meaning that each variable contains an object
reference rather than a copy of the entire object.
3
OBJECT ORIENTED PROGRAMMING IN PHP
OBJECT ORIENTED CONCEPTS
▸ Class − This is a programmer-defined data type, which includes local functions as well
as local data. You can think of a class as a template for making many instances of the
same kind (or class) of object.
▸ Object − An individual instance of the data structure defined by a class. You define a
class once and then make many objects that belong to it. Objects are also known as
instance.
▸ Member Variable − These are the variables defined inside a class. This data will be
invisible to the outside of the class and can be accessed via member functions. These
variables are called attribute of the object once an object is created.
▸ Member function − These are the function defined inside a class and are used to
access object data.
▸ Inheritance − When a class is defined by inheriting existing function of a parent class
then it is called inheritance. Here child class will inherit all or few member functions
and variables of a parent class.
4
OBJECT ORIENTED PROGRAMMING IN PHP
OBJECT ORIENTED CONCEPTS
▸ Parent class − A class that is inherited from by another class. This is also called a base class or super class.
▸ Child Class − A class that inherits from another class. This is also called a subclass or derived class.
▸ Polymorphism − This is an object oriented concept where same function can be used for different
purposes. For example function name will remain same but it make take different number of arguments
and can do different task.
▸ Overloading − a type of polymorphism in which some or all of operators have different implementations
depending on the types of their arguments. Similarly functions can also be overloaded with different
implementation.
▸ Data Abstraction − Any representation of data in which the implementation details are hidden
(abstracted).
▸ Encapsulation − refers to a concept where we encapsulate all the data and member functions together to
form an object.
▸ Constructor − refers to a special type of function which will be called automatically whenever there is an
object formation from a class.
▸ Destructor − refers to a special type of function which will be called automatically whenever an object is
deleted or goes out of scope.
5
ADVANCED PHP
STRUCTURING CLASSES
<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj); // output: object(MyClass)#1 (0) { }
6
ADVANCED PHP
DEFINING CLASS PROPERTIES
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
}
$obj = new MyClass;
echo $obj->prop1; // Output: I'm a class property!
7
ADVANCED PHP
DEFINING CLASS METHODS
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1;
}
}
$obj = new MyClass;
echo $obj->getProperty(); // Get the property value, outputs: I'm a class property!
$obj->setProperty("I'm a new property value!"); // Set a new one
echo $obj->getProperty(); // Read it out again to show the change, outputs: I'm a new property
value!
8
ADVANCED PHP
OBJECTS
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1;
}
}
// Create two objects
$obj = new MyClass;
$obj2 = new MyClass;
// Get the value of $prop1 from both objects
echo $obj->getProperty();
echo $obj2->getProperty();
// Set new values for both objects
$obj->setProperty("I'm a new property value!");
$obj2->setProperty("I belong to the second instance!");
// Output both objects' $prop1 value
echo $obj->getProperty();
echo $obj2->getProperty();
9
OBJECT ORIENTED PROGRAMMING IN PHP
MAGIC METHODS IN PHP OOP
▸ To make the use of objects easier, PHP also provides a
number of magic methods, or special methods that are
called when certain common actions occur within objects.
▸ This allows developers to perform a number of useful
tasks with relative ease.
▸ The function names __construct(), __destruct(),
__call(), __callStatic(), __get(), __set(),
__isset(), __unset(), __sleep(), __wakeup(),
__toString(), __invoke(), __set_state(),
__clone() and __debugInfo()
10
ADVANCED PHP
CONSTRUCTOR & DESCTRUCTOR
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.';
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1;
}
}
// Create a new object
$obj = new MyClass;
// Get the value of $prop1
echo $obj->getProperty();
// Destroy the object
unset($obj);
// Output a message at the end of the file
echo "End of file.";
11
ADVANCED PHP
CONVERTING TO STRING
<?php
// Output the object as a string
echo $obj; // outputs: Catchable fatal error: Object of class MyClass could not be converted to string
class MyClass
{
// ...
public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}
// ...
}
// Create a new object
$obj = new MyClass;
// Output the object as a string
echo $obj; // outputs: Using the toString method: I'm a class property!
// Destroy the object
unset($obj);
// Output a message at the end of the file
echo "End of file.";
12
ADVANCED PHP
USING CLASS INHERITANCE
<?php
class MyOtherClass extends MyClass
{
public function newMethod()
{
echo "From a new method in " . __CLASS__;
}
}
// Create a new object
$newobj = new MyOtherClass;
// Output the object as a string
echo $newobj->newMethod(); // outputs: From a new method in MyOtherClass.
// Use a method from the parent class
echo $newobj->getProperty(); // outputs: I'm a class property!
13
ADVANCED PHP
OVERWRITING INHERITED PROPERTIES AND METHODS
<?php
class MyOtherClass extends MyClass
{
public function __construct()
{
echo "A new constructor in " . __CLASS__;
}
public function newMethod()
{
echo "From a new method in " . __CLASS__;
}
}
// Create a new object
$newobj = new MyOtherClass; // outputs: A new constructor in MyOtherClass.
// Output the object as a string
echo $newobj->newMethod(); // outputs: From a new method in MyOtherClass.
// Use a method from the parent class
echo $newobj->getProperty(); // outputs: I'm a class property!
14
ADVANCED PHP
PRESERVING ORIGINAL METHOD FUNCTIONALITY WHILE OVERWRITING METHODS
<?php
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct(); // Call the parent class's constructor using scope resolution
operator (::)
echo "A new constructor in " . __CLASS__;
}
public function newMethod()
{
echo "From a new method in " . __CLASS__;
}
}
// Create a new object
$newobj = new MyOtherClass;
// Output the object as a string
echo $newobj->newMethod();
// Use a method from the parent class
echo $newobj->getProperty();
15
OBJECT ORIENTED PROGRAMMING IN PHP
ASSIGNING THE VISIBILITY OF PROPERTIES AND METHODS
▸ For added control over objects, methods and properties
are assigned visibility.
▸ This controls how and from where properties and methods
can be accessed.
▸ There are three visibility keywords: public, protected,
and private.
▸ In addition to its visibility, a method or property can be
declared as static, which allows them to be accessed
without an instantiation of the class.
16
ADVANCED PHP
PROTECTED PROPERTIES AND METHODS
<?php
class MyClass
{
// ..
public function setProperty($newval)
{
$this->prop1 = $newval;
}
protected function getProperty()
{
return $this->prop1;
}
}
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct();
echo "A new constructor in " . __CLASS__;
}
public function newMethod()
{
echo "From a new method in " . __CLASS__;
}
}
// Create a new object
$newobj = new MyOtherClass;
// Attempt to call a protected method
echo $newobj->getProperty(); // outputs: Fatal error: Call to protected method MyClass::getProperty() from context ''
17
ADVANCED PHP
PROTECTED PROPERTIES AND METHODS
<?php
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct();
echo "A new constructor in " . __CLASS__ . ".<br />";
}
public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
public function callProtected()
{
return $this->getProperty();
}
// Create a new object
$newobj = new MyOtherClass;
// Attempt to call a protected method
echo $newobj->callProtected();
18
ADVANCED PHP
PRIVATE PROPERTIES AND METHODS
<?php
class MyClass
{
// ..
private function getProperty()
{
return $this->prop1;
}
}
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct();
echo "A new constructor in " . __CLASS__;
}
public function newMethod()
{
echo "From a new method in " . __CLASS__;
}
public function callProtected()
{
return $this->getProperty();
}
}
// Create a new object
$newobj = new MyOtherClass;
// Use a method from the parent class
echo $newobj->callProtected(); // outputs: Fatal error: Call to private method MyClass::getProperty() from context 'MyOtherClass'
19
ADVANCED PHP
STATIC PROPERTIES AND METHODS
<?php
/*
A method or property declared static can be accessed without first instantiating the class; you
simply supply the class name, scope resolution operator, and the property or method name.
*/
class MyClass
{
// ...
public static $count = 0;
// ...
public static function plusOne()
{
return "The count is " . ++self::$count;
}
}
do { // Call plusOne without instantiating MyClass
echo MyClass::plusOne();
} while ( MyClass::$count < 10 );
20
ADVANCED PHP
ABSTRACT CLASSES AND METHODS
<?php
abstract class Car {
// Abstract classes can have properties
protected $tankVolume;
// Abstract classes can have non abstract methods
public function setTankVolume($volume)
{
$this -> tankVolume = $volume;
}
// Abstract method
abstract public function calcNumMilesOnFullTank();
}
class Honda extends Car {
// Since we inherited abstract method, we need to define it in the child class,
// by adding code to the method's body.
public function calcNumMilesOnFullTank()
{
$miles = $this -> tankVolume*30;
return $miles;
}
public function getColor()
{
return "beige";
}
}
21
ADVANCED PHP
INTERFACES
<?php
/* Interfaces resemble abstract classes in that they include abstract methods that the programmer must define in the classes that inherit
from the interface. In this way, interfaces contribute to code organization because they commit the child classes to abstract methods that
they should implement.*/
interface Car {
public function setModel($name);
public function getModel();
}
interface Vehicle {
public function setHasWheels($bool);
public function getHasWheels();
}
class miniCar implements Car, Vehicle {
private $model;
private $hasWheels;
public function setModel($name)
{
$this -> model = $name;
}
public function getModel()
{
return $this -> model;
}
public function setHasWheels($bool)
{
$this -> hasWheels = $bool;
}
public function getHasWheels()
{
return ($this -> hasWheels)? "has wheels" : "no wheels";
}
}
22
OBJECT ORIENTED PROGRAMMING IN PHP
DIFFERENCES BETWEEN ABSTRACT CLASSES AND INTERFACES
23
interface abstract class
the code
- abstract methods
- constants
- abstract methods
- constants
- concrete methods
- concrete variables
access
modifiers
- public
- - public
- - private
- - protected
- - static
number of
parents
The same class can implement
more than 1 interface
The child class can inherit only
from 1 abstract class
ADVANCED PHP
POLYMORPHISM
<?php
/* According to the Polymorphism principle, methods in different classes that do similar things should have the same name. */
interface Shape {
public function calcArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius)
{
$this -> radius = $radius;
}
public function calcArea() // calcArea calculates the area of circles
{
return $this -> radius * $this -> radius * pi();
}
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height)
{
$this -> width = $width;
$this -> height = $height;
}
public function calcArea() // calcArea calculates the area of rectangles
{
return $this -> width * $this -> height;
}
}
$circ = new Circle(3);
$rect = new Rectangle(3,4);
echo $circ -> calcArea();
echo $rect -> calcArea();
24
ADVANCED PHP
TYPE HINTING
<?php
// The function can only get array as an argument.
function calcNumMilesOnFullTank(array $models)
{
foreach ($models as $item) {
echo $carModel = $item[0];
echo " : ";
echo $numberOfMiles = $item[1] * $item[2];
}
}
calcNumMilesOnFullTank("Toyota"); // outputs: Catchable fatal error: Argument 1 passed to calcNumMilesOnFullTank() must be of the
type array, string given
$models = array(
array('Toyota', 12, 44),
array('BMW', 13, 41)
);
calcNumMilesOnFullTank($models);
class Car {
protected $driver;
// The constructor can only get Driver objects as arguments.
public function __construct(Driver $driver)
{
$this -> driver = $driver;
}
}
class Driver {}
$driver1 = new Driver();
$car1 = new Car($driver1);
25
ADVANCED PHP
TYPE HINTING IN PHP7
<?php
class car {
protected $model;
protected $hasSunRoof;
protected $numberOfDoors;
protected $price;
// string type hinting
public function setModel(string $model)
{
$this->model = $model;
}
// boolean type hinting
public function setHasSunRoof(bool $value)
{
$this->hasSunRoof = $value;
}
// integer type hinting
public function setNumberOfDoors(int $value)
{
$this->numberOfDoors = $value;
}
// float type hinting
public function setPrice(float $value)
{
$this->price = $value;
}
}
26
ADVANCED PHP
NAMESPACES
<?php
// application library 1 - lib1.php
namespace AppLib1;
const MYCONST = 'AppLib1MYCONST';
function MyFunction() {
return __FUNCTION__;
}
class MyClass {
static function WhoAmI() {
return __METHOD__;
}
}
/* ---------------------------------- */
require_once(‘lib1.php');
echo AppLib1MYCONST; // outputs: AppLib1MYCONST
echo AppLib1MyFunction(); // outputs: AppLib1MyFunction
echo AppLib1MyClass::WhoAmI(); // outputs: AppLib1MyClass::WhoAmI
27
ADVANCED PHP
NAMESPACES - WITHIN THE SAME NAMESPACE
<?php
// application library 2 -- lib2.php
namespace AppLib2;
const MYCONST = 'AppLib2MYCONST';
function MyFunction() {
return __FUNCTION__;
}
class MyClass {
static function WhoAmI() {
return __METHOD__;
}
}
/* ---------------------------------- */
namespace AppLib1;
require_once('lib1.php');
require_once('lib2.php');
echo MYCONST; // outputs: AppLib1MYCONST
echo MyFunction(); // outputs: AppLib1MyFunction
echo MyClass::WhoAmI(); //outputs AppLib1MyClass::WhoAmI
28
ADVANCED PHP
NAMESPACES - IMPORTING
<?php
use AppLib2;
require_once('lib1.php');
require_once('lib2.php');
echo Lib2MYCONST; // outputs: AppLib2MYCONST
echo Lib2MyFunction(); // outputs: AppLib2MyFunction
echo Lib2MyClass::WhoAmI(); // outputs: AppLib2MyClass::WhoAmI
29
ADVANCED PHP
NAMESPACES - ALIASES
<?php
use AppLib1 as L;
use AppLib2MyClass as Obj;
require_once('lib1.php');
require_once('lib2.php');
echo LMYCONST; // outputs: AppLib1MYCONST
echo LMyFunction(); // outputs: AppLib1MyFunction
echo LMyClass::WhoAmI(); // outputs: AppLib1MyClass::WhoAmI
echo Obj::WhoAmI(); // outputs: AppLib2MyClass::WhoAmI
30
ADVANCED PHP
TRAITS
<?php
/* Traits are a mechanism for code reuse in single inheritance languages. A Trait is
intended to reduce some limitations of single inheritance by enabling a developer to
reuse sets of methods freely in several independent classes living in different class
hierarchies */
trait ezcReflectionReturnInfo {
function getReturnType() { /*1*/ }
function getReturnDescription() { /*2*/ }
}
class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
/* ... */
}
class ezcReflectionFunction extends ReflectionFunction {
use ezcReflectionReturnInfo;
/* ... */
}
31
ADVANCED PHP
TRAITS
<?php
class Base
{
public function sayHello()
{
echo 'Hello ';
}
}
trait SayWorld
{
public function sayHello()
{
parent::sayHello();
echo 'World!';
}
}
class MyHelloWorld extends Base
{
use SayWorld;
}
$o = new MyHelloWorld();
$o->sayHello(); // outputs: Hello World!
32
ADVANCED PHP
TRAITS
<?php
trait HelloWorld {
public function sayHello() {
echo 'Hello World!';
}
}
class TheWorldIsNotEnough {
use HelloWorld;
public function sayHello() {
echo 'Hello Universe!';
}
}
$o = new TheWorldIsNotEnough();
$o->sayHello(); // outputs: Hello Universe!
33
ADVANCED PHP
TRAITS
<?php
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}
trait World {
public function sayWorld() {
echo 'World';
}
}
class MyHelloWorld {
use Hello, World;
public function sayExclamationMark() {
echo '!';
}
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark(); // outputs: Hello World!
34
ADVANCED PHP
COMMENTING WITH DOCBLOCKS
<?php
/**
* A simple class
*
* This is the long description for this class,
* which can span as many lines as needed. It is
* not required, whereas the short description is
* necessary.
*
* @author Denis Ristic <denis.ristic@perpetuum.hr>
* @copyright 2017 Perpetuum Mobile
* @license http://www.php.net/license/3_01.txt PHP License 3.01
*/
class SimpleClass
{
/**
* A public variable
*
* @var string stores data for the class
*/
public $foo;
/**
* Sets $foo to a new value upon class instantiation
*
* @param string $val a value required for the class
* @return void
*/
public function __construct($val)
{
$this->foo = $val;
}
/**
* Multiplies two integers
*
* Accepts a pair of integers and returns the
* product of the two.
*
* @param int $bat a number to be multiplied
* @param int $baz a number to be multiplied
* @return int the product of the two parameters
*/
public function bar($bat, $baz)
{
return $bat * $baz;
}
}
35

More Related Content

PPT
PHP- Introduction to Object Oriented PHP
PPT
PHP - Introduction to Object Oriented Programming with PHP
PDF
OOP in PHP
PPT
Oops in PHP
PPT
Class 7 - PHP Object Oriented Programming
PPT
Oops concepts in php
PPTX
Object oreinted php | OOPs
PDF
A Gentle Introduction To Object Oriented Php
PHP- Introduction to Object Oriented PHP
PHP - Introduction to Object Oriented Programming with PHP
OOP in PHP
Oops in PHP
Class 7 - PHP Object Oriented Programming
Oops concepts in php
Object oreinted php | OOPs
A Gentle Introduction To Object Oriented Php

What's hot (20)

PPT
Introduction to OOP with PHP
PPTX
Object oriented programming in php 5
PDF
Object Oriented Programming with PHP 5 - More OOP
PPTX
Oop in-php
PPT
Php Oop
PPTX
Only oop
PPT
Synapseindia object oriented programming in php
PPTX
FFW Gabrovo PMG - PHP OOP Part 3
PDF
Object Oriented Programming in PHP
ZIP
Object Oriented PHP5
PPTX
Introduction to PHP OOP
PPT
Advanced php
PPTX
Php oop presentation
PDF
Intermediate OOP in PHP
PPTX
Intro to OOP PHP and Github
PPT
Oops in PHP By Nyros Developer
PPTX
OOPS Characteristics (With Examples in PHP)
PPT
Class and Objects in PHP
Introduction to OOP with PHP
Object oriented programming in php 5
Object Oriented Programming with PHP 5 - More OOP
Oop in-php
Php Oop
Only oop
Synapseindia object oriented programming in php
FFW Gabrovo PMG - PHP OOP Part 3
Object Oriented Programming in PHP
Object Oriented PHP5
Introduction to PHP OOP
Advanced php
Php oop presentation
Intermediate OOP in PHP
Intro to OOP PHP and Github
Oops in PHP By Nyros Developer
OOPS Characteristics (With Examples in PHP)
Class and Objects in PHP
Ad

Similar to 09 Object Oriented Programming in PHP #burningkeyboards (20)

PPTX
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
PPTX
UNIT III (8).pptx
PPTX
UNIT III (8).pptx
PPTX
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
PPTX
Object oriented programming in php
PPTX
Ch8(oop)
PPTX
Oops in php
PPT
Basic Oops concept of PHP
PPT
Introduction Php
PDF
Object_oriented_programming_OOP_with_PHP.pdf
PDF
OOP in PHP
PPTX
PHP OOP Lecture - 03.pptx
PDF
Object Oriented Programming in PHP
PPT
Oop in php lecture 2
PDF
Demystifying Object-Oriented Programming #ssphp16
PPT
Php object orientation and classes
DOCX
Oops concept in php
PPTX
Lecture-10_PHP-OOP.pptx
PPTX
Lecture9_OOPHP_SPring2023.pptx
PDF
Demystifying Object-Oriented Programming #phpbnl18
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
UNIT III (8).pptx
UNIT III (8).pptx
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
Object oriented programming in php
Ch8(oop)
Oops in php
Basic Oops concept of PHP
Introduction Php
Object_oriented_programming_OOP_with_PHP.pdf
OOP in PHP
PHP OOP Lecture - 03.pptx
Object Oriented Programming in PHP
Oop in php lecture 2
Demystifying Object-Oriented Programming #ssphp16
Php object orientation and classes
Oops concept in php
Lecture-10_PHP-OOP.pptx
Lecture9_OOPHP_SPring2023.pptx
Demystifying Object-Oriented Programming #phpbnl18
Ad

More from Denis Ristic (20)

PDF
Magento Continuous Integration & Continuous Delivery @MM17HR
PDF
Continuous integration & Continuous Delivery @DeVz
PDF
25 Intro to Symfony #burningkeyboards
PDF
24 Scrum #burningkeyboards
PDF
23 LAMP Stack #burningkeyboards
PDF
22 REST & JSON API Design #burningkeyboards
PDF
21 HTTP Protocol #burningkeyboards
PDF
20 PHP Static Analysis and Documentation Generators #burningkeyboards
PDF
19 GitFlow #burningkeyboards
PDF
18 Git #burningkeyboards
PDF
17 Linux Basics #burningkeyboards
PDF
16 MySQL Optimization #burningkeyboards
PDF
15 MySQL Basics #burningkeyboards
PDF
14 Dependency Injection #burningkeyboards
PDF
13 PHPUnit #burningkeyboards
PDF
12 Composer #burningkeyboards
PDF
11 PHP Security #burningkeyboards
PDF
10 PHP Design Patterns #burningkeyboards
PDF
08 Advanced PHP #burningkeyboards
PDF
07 Introduction to PHP #burningkeyboards
Magento Continuous Integration & Continuous Delivery @MM17HR
Continuous integration & Continuous Delivery @DeVz
25 Intro to Symfony #burningkeyboards
24 Scrum #burningkeyboards
23 LAMP Stack #burningkeyboards
22 REST & JSON API Design #burningkeyboards
21 HTTP Protocol #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboards
19 GitFlow #burningkeyboards
18 Git #burningkeyboards
17 Linux Basics #burningkeyboards
16 MySQL Optimization #burningkeyboards
15 MySQL Basics #burningkeyboards
14 Dependency Injection #burningkeyboards
13 PHPUnit #burningkeyboards
12 Composer #burningkeyboards
11 PHP Security #burningkeyboards
10 PHP Design Patterns #burningkeyboards
08 Advanced PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
KodekX | Application Modernization Development
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Big Data Technologies - Introduction.pptx
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
cuic standard and advanced reporting.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Advanced IT Governance
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
“AI and Expert System Decision Support & Business Intelligence Systems”
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
KodekX | Application Modernization Development
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Big Data Technologies - Introduction.pptx
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Chapter 2 Digital Image Fundamentals.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
cuic standard and advanced reporting.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Review of recent advances in non-invasive hemoglobin estimation
Reach Out and Touch Someone: Haptics and Empathic Computing
madgavkar20181017ppt McKinsey Presentation.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Advanced IT Governance
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy

09 Object Oriented Programming in PHP #burningkeyboards

  • 3. OBJECT ORIENTED PROGRAMMING IN PHP INTRO TO OOP ▸ Object-oriented programming is a style of coding that allows developers to group similar tasks into classes. ▸ PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. 3
  • 4. OBJECT ORIENTED PROGRAMMING IN PHP OBJECT ORIENTED CONCEPTS ▸ Class − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object. ▸ Object − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance. ▸ Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created. ▸ Member function − These are the function defined inside a class and are used to access object data. ▸ Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class. 4
  • 5. OBJECT ORIENTED PROGRAMMING IN PHP OBJECT ORIENTED CONCEPTS ▸ Parent class − A class that is inherited from by another class. This is also called a base class or super class. ▸ Child Class − A class that inherits from another class. This is also called a subclass or derived class. ▸ Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it make take different number of arguments and can do different task. ▸ Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation. ▸ Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted). ▸ Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object. ▸ Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class. ▸ Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope. 5
  • 6. ADVANCED PHP STRUCTURING CLASSES <?php class MyClass { // Class properties and methods go here } $obj = new MyClass; var_dump($obj); // output: object(MyClass)#1 (0) { } 6
  • 7. ADVANCED PHP DEFINING CLASS PROPERTIES <?php class MyClass { public $prop1 = "I'm a class property!"; } $obj = new MyClass; echo $obj->prop1; // Output: I'm a class property! 7
  • 8. ADVANCED PHP DEFINING CLASS METHODS <?php class MyClass { public $prop1 = "I'm a class property!"; public function setProperty($newval) { $this->prop1 = $newval; } public function getProperty() { return $this->prop1; } } $obj = new MyClass; echo $obj->getProperty(); // Get the property value, outputs: I'm a class property! $obj->setProperty("I'm a new property value!"); // Set a new one echo $obj->getProperty(); // Read it out again to show the change, outputs: I'm a new property value! 8
  • 9. ADVANCED PHP OBJECTS <?php class MyClass { public $prop1 = "I'm a class property!"; public function setProperty($newval) { $this->prop1 = $newval; } public function getProperty() { return $this->prop1; } } // Create two objects $obj = new MyClass; $obj2 = new MyClass; // Get the value of $prop1 from both objects echo $obj->getProperty(); echo $obj2->getProperty(); // Set new values for both objects $obj->setProperty("I'm a new property value!"); $obj2->setProperty("I belong to the second instance!"); // Output both objects' $prop1 value echo $obj->getProperty(); echo $obj2->getProperty(); 9
  • 10. OBJECT ORIENTED PROGRAMMING IN PHP MAGIC METHODS IN PHP OOP ▸ To make the use of objects easier, PHP also provides a number of magic methods, or special methods that are called when certain common actions occur within objects. ▸ This allows developers to perform a number of useful tasks with relative ease. ▸ The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo() 10
  • 11. ADVANCED PHP CONSTRUCTOR & DESCTRUCTOR <?php class MyClass { public $prop1 = "I'm a class property!"; public function __construct() { echo 'The class "', __CLASS__, '" was initiated!'; } public function __destruct() { echo 'The class "', __CLASS__, '" was destroyed.'; } public function setProperty($newval) { $this->prop1 = $newval; } public function getProperty() { return $this->prop1; } } // Create a new object $obj = new MyClass; // Get the value of $prop1 echo $obj->getProperty(); // Destroy the object unset($obj); // Output a message at the end of the file echo "End of file."; 11
  • 12. ADVANCED PHP CONVERTING TO STRING <?php // Output the object as a string echo $obj; // outputs: Catchable fatal error: Object of class MyClass could not be converted to string class MyClass { // ... public function __toString() { echo "Using the toString method: "; return $this->getProperty(); } // ... } // Create a new object $obj = new MyClass; // Output the object as a string echo $obj; // outputs: Using the toString method: I'm a class property! // Destroy the object unset($obj); // Output a message at the end of the file echo "End of file."; 12
  • 13. ADVANCED PHP USING CLASS INHERITANCE <?php class MyOtherClass extends MyClass { public function newMethod() { echo "From a new method in " . __CLASS__; } } // Create a new object $newobj = new MyOtherClass; // Output the object as a string echo $newobj->newMethod(); // outputs: From a new method in MyOtherClass. // Use a method from the parent class echo $newobj->getProperty(); // outputs: I'm a class property! 13
  • 14. ADVANCED PHP OVERWRITING INHERITED PROPERTIES AND METHODS <?php class MyOtherClass extends MyClass { public function __construct() { echo "A new constructor in " . __CLASS__; } public function newMethod() { echo "From a new method in " . __CLASS__; } } // Create a new object $newobj = new MyOtherClass; // outputs: A new constructor in MyOtherClass. // Output the object as a string echo $newobj->newMethod(); // outputs: From a new method in MyOtherClass. // Use a method from the parent class echo $newobj->getProperty(); // outputs: I'm a class property! 14
  • 15. ADVANCED PHP PRESERVING ORIGINAL METHOD FUNCTIONALITY WHILE OVERWRITING METHODS <?php class MyOtherClass extends MyClass { public function __construct() { parent::__construct(); // Call the parent class's constructor using scope resolution operator (::) echo "A new constructor in " . __CLASS__; } public function newMethod() { echo "From a new method in " . __CLASS__; } } // Create a new object $newobj = new MyOtherClass; // Output the object as a string echo $newobj->newMethod(); // Use a method from the parent class echo $newobj->getProperty(); 15
  • 16. OBJECT ORIENTED PROGRAMMING IN PHP ASSIGNING THE VISIBILITY OF PROPERTIES AND METHODS ▸ For added control over objects, methods and properties are assigned visibility. ▸ This controls how and from where properties and methods can be accessed. ▸ There are three visibility keywords: public, protected, and private. ▸ In addition to its visibility, a method or property can be declared as static, which allows them to be accessed without an instantiation of the class. 16
  • 17. ADVANCED PHP PROTECTED PROPERTIES AND METHODS <?php class MyClass { // .. public function setProperty($newval) { $this->prop1 = $newval; } protected function getProperty() { return $this->prop1; } } class MyOtherClass extends MyClass { public function __construct() { parent::__construct(); echo "A new constructor in " . __CLASS__; } public function newMethod() { echo "From a new method in " . __CLASS__; } } // Create a new object $newobj = new MyOtherClass; // Attempt to call a protected method echo $newobj->getProperty(); // outputs: Fatal error: Call to protected method MyClass::getProperty() from context '' 17
  • 18. ADVANCED PHP PROTECTED PROPERTIES AND METHODS <?php class MyOtherClass extends MyClass { public function __construct() { parent::__construct(); echo "A new constructor in " . __CLASS__ . ".<br />"; } public function newMethod() { echo "From a new method in " . __CLASS__ . ".<br />"; } public function callProtected() { return $this->getProperty(); } // Create a new object $newobj = new MyOtherClass; // Attempt to call a protected method echo $newobj->callProtected(); 18
  • 19. ADVANCED PHP PRIVATE PROPERTIES AND METHODS <?php class MyClass { // .. private function getProperty() { return $this->prop1; } } class MyOtherClass extends MyClass { public function __construct() { parent::__construct(); echo "A new constructor in " . __CLASS__; } public function newMethod() { echo "From a new method in " . __CLASS__; } public function callProtected() { return $this->getProperty(); } } // Create a new object $newobj = new MyOtherClass; // Use a method from the parent class echo $newobj->callProtected(); // outputs: Fatal error: Call to private method MyClass::getProperty() from context 'MyOtherClass' 19
  • 20. ADVANCED PHP STATIC PROPERTIES AND METHODS <?php /* A method or property declared static can be accessed without first instantiating the class; you simply supply the class name, scope resolution operator, and the property or method name. */ class MyClass { // ... public static $count = 0; // ... public static function plusOne() { return "The count is " . ++self::$count; } } do { // Call plusOne without instantiating MyClass echo MyClass::plusOne(); } while ( MyClass::$count < 10 ); 20
  • 21. ADVANCED PHP ABSTRACT CLASSES AND METHODS <?php abstract class Car { // Abstract classes can have properties protected $tankVolume; // Abstract classes can have non abstract methods public function setTankVolume($volume) { $this -> tankVolume = $volume; } // Abstract method abstract public function calcNumMilesOnFullTank(); } class Honda extends Car { // Since we inherited abstract method, we need to define it in the child class, // by adding code to the method's body. public function calcNumMilesOnFullTank() { $miles = $this -> tankVolume*30; return $miles; } public function getColor() { return "beige"; } } 21
  • 22. ADVANCED PHP INTERFACES <?php /* Interfaces resemble abstract classes in that they include abstract methods that the programmer must define in the classes that inherit from the interface. In this way, interfaces contribute to code organization because they commit the child classes to abstract methods that they should implement.*/ interface Car { public function setModel($name); public function getModel(); } interface Vehicle { public function setHasWheels($bool); public function getHasWheels(); } class miniCar implements Car, Vehicle { private $model; private $hasWheels; public function setModel($name) { $this -> model = $name; } public function getModel() { return $this -> model; } public function setHasWheels($bool) { $this -> hasWheels = $bool; } public function getHasWheels() { return ($this -> hasWheels)? "has wheels" : "no wheels"; } } 22
  • 23. OBJECT ORIENTED PROGRAMMING IN PHP DIFFERENCES BETWEEN ABSTRACT CLASSES AND INTERFACES 23 interface abstract class the code - abstract methods - constants - abstract methods - constants - concrete methods - concrete variables access modifiers - public - - public - - private - - protected - - static number of parents The same class can implement more than 1 interface The child class can inherit only from 1 abstract class
  • 24. ADVANCED PHP POLYMORPHISM <?php /* According to the Polymorphism principle, methods in different classes that do similar things should have the same name. */ interface Shape { public function calcArea(); } class Circle implements Shape { private $radius; public function __construct($radius) { $this -> radius = $radius; } public function calcArea() // calcArea calculates the area of circles { return $this -> radius * $this -> radius * pi(); } } class Rectangle implements Shape { private $width; private $height; public function __construct($width, $height) { $this -> width = $width; $this -> height = $height; } public function calcArea() // calcArea calculates the area of rectangles { return $this -> width * $this -> height; } } $circ = new Circle(3); $rect = new Rectangle(3,4); echo $circ -> calcArea(); echo $rect -> calcArea(); 24
  • 25. ADVANCED PHP TYPE HINTING <?php // The function can only get array as an argument. function calcNumMilesOnFullTank(array $models) { foreach ($models as $item) { echo $carModel = $item[0]; echo " : "; echo $numberOfMiles = $item[1] * $item[2]; } } calcNumMilesOnFullTank("Toyota"); // outputs: Catchable fatal error: Argument 1 passed to calcNumMilesOnFullTank() must be of the type array, string given $models = array( array('Toyota', 12, 44), array('BMW', 13, 41) ); calcNumMilesOnFullTank($models); class Car { protected $driver; // The constructor can only get Driver objects as arguments. public function __construct(Driver $driver) { $this -> driver = $driver; } } class Driver {} $driver1 = new Driver(); $car1 = new Car($driver1); 25
  • 26. ADVANCED PHP TYPE HINTING IN PHP7 <?php class car { protected $model; protected $hasSunRoof; protected $numberOfDoors; protected $price; // string type hinting public function setModel(string $model) { $this->model = $model; } // boolean type hinting public function setHasSunRoof(bool $value) { $this->hasSunRoof = $value; } // integer type hinting public function setNumberOfDoors(int $value) { $this->numberOfDoors = $value; } // float type hinting public function setPrice(float $value) { $this->price = $value; } } 26
  • 27. ADVANCED PHP NAMESPACES <?php // application library 1 - lib1.php namespace AppLib1; const MYCONST = 'AppLib1MYCONST'; function MyFunction() { return __FUNCTION__; } class MyClass { static function WhoAmI() { return __METHOD__; } } /* ---------------------------------- */ require_once(‘lib1.php'); echo AppLib1MYCONST; // outputs: AppLib1MYCONST echo AppLib1MyFunction(); // outputs: AppLib1MyFunction echo AppLib1MyClass::WhoAmI(); // outputs: AppLib1MyClass::WhoAmI 27
  • 28. ADVANCED PHP NAMESPACES - WITHIN THE SAME NAMESPACE <?php // application library 2 -- lib2.php namespace AppLib2; const MYCONST = 'AppLib2MYCONST'; function MyFunction() { return __FUNCTION__; } class MyClass { static function WhoAmI() { return __METHOD__; } } /* ---------------------------------- */ namespace AppLib1; require_once('lib1.php'); require_once('lib2.php'); echo MYCONST; // outputs: AppLib1MYCONST echo MyFunction(); // outputs: AppLib1MyFunction echo MyClass::WhoAmI(); //outputs AppLib1MyClass::WhoAmI 28
  • 29. ADVANCED PHP NAMESPACES - IMPORTING <?php use AppLib2; require_once('lib1.php'); require_once('lib2.php'); echo Lib2MYCONST; // outputs: AppLib2MYCONST echo Lib2MyFunction(); // outputs: AppLib2MyFunction echo Lib2MyClass::WhoAmI(); // outputs: AppLib2MyClass::WhoAmI 29
  • 30. ADVANCED PHP NAMESPACES - ALIASES <?php use AppLib1 as L; use AppLib2MyClass as Obj; require_once('lib1.php'); require_once('lib2.php'); echo LMYCONST; // outputs: AppLib1MYCONST echo LMyFunction(); // outputs: AppLib1MyFunction echo LMyClass::WhoAmI(); // outputs: AppLib1MyClass::WhoAmI echo Obj::WhoAmI(); // outputs: AppLib2MyClass::WhoAmI 30
  • 31. ADVANCED PHP TRAITS <?php /* Traits are a mechanism for code reuse in single inheritance languages. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies */ trait ezcReflectionReturnInfo { function getReturnType() { /*1*/ } function getReturnDescription() { /*2*/ } } class ezcReflectionMethod extends ReflectionMethod { use ezcReflectionReturnInfo; /* ... */ } class ezcReflectionFunction extends ReflectionFunction { use ezcReflectionReturnInfo; /* ... */ } 31
  • 32. ADVANCED PHP TRAITS <?php class Base { public function sayHello() { echo 'Hello '; } } trait SayWorld { public function sayHello() { parent::sayHello(); echo 'World!'; } } class MyHelloWorld extends Base { use SayWorld; } $o = new MyHelloWorld(); $o->sayHello(); // outputs: Hello World! 32
  • 33. ADVANCED PHP TRAITS <?php trait HelloWorld { public function sayHello() { echo 'Hello World!'; } } class TheWorldIsNotEnough { use HelloWorld; public function sayHello() { echo 'Hello Universe!'; } } $o = new TheWorldIsNotEnough(); $o->sayHello(); // outputs: Hello Universe! 33
  • 34. ADVANCED PHP TRAITS <?php trait Hello { public function sayHello() { echo 'Hello '; } } trait World { public function sayWorld() { echo 'World'; } } class MyHelloWorld { use Hello, World; public function sayExclamationMark() { echo '!'; } } $o = new MyHelloWorld(); $o->sayHello(); $o->sayWorld(); $o->sayExclamationMark(); // outputs: Hello World! 34
  • 35. ADVANCED PHP COMMENTING WITH DOCBLOCKS <?php /** * A simple class * * This is the long description for this class, * which can span as many lines as needed. It is * not required, whereas the short description is * necessary. * * @author Denis Ristic <[email protected]> * @copyright 2017 Perpetuum Mobile * @license http://www.php.net/license/3_01.txt PHP License 3.01 */ class SimpleClass { /** * A public variable * * @var string stores data for the class */ public $foo; /** * Sets $foo to a new value upon class instantiation * * @param string $val a value required for the class * @return void */ public function __construct($val) { $this->foo = $val; } /** * Multiplies two integers * * Accepts a pair of integers and returns the * product of the two. * * @param int $bat a number to be multiplied * @param int $baz a number to be multiplied * @return int the product of the two parameters */ public function bar($bat, $baz) { return $bat * $baz; } } 35
  • 36. OBJECT ORIENTED PROGRAMMING IN PHP PHP OOP REFERENCES ▸ PHP Documentation ▸ http://php.net/manual/en/language.oop5.php ▸ Object-Oriented PHP for Beginners ▸ https://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762 ▸ Learn Object-oriented PHP ▸ http://phpenthusiast.com/object-oriented-php-tutorials ▸ How to Use PHP Namespaces ▸ https://www.sitepoint.com/php-53-namespaces-basics/ ▸ PHP Trait ▸ https://tutorials.kode-blog.com/blog/php-trait 36