SlideShare a Scribd company logo
1 of 35
Download to read offline
#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

What's hot

Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5Sayed Ahmed
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPWildan Maulana
 
Oop in-php
Oop in-phpOop in-php
Oop in-phpRajesh S
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindiappsdevelopment
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3Toni Kolev
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5Jason Austin
 
Introduction to PHP OOP
Introduction to PHP OOPIntroduction to PHP OOP
Introduction to PHP OOPfakhrul hasan
 
Advanced php
Advanced phpAdvanced php
Advanced phphamfu
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHPDavid Stockton
 
Intro to OOP PHP and Github
Intro to OOP PHP and GithubIntro to OOP PHP and Github
Intro to OOP PHP and GithubJo Erik San Jose
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperNyros Technologies
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHPRamasubbu .P
 

What's hot (20)

Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
 
Oop in-php
Oop in-phpOop in-php
Oop in-php
 
Php Oop
Php OopPhp Oop
Php Oop
 
Only oop
Only oopOnly oop
Only oop
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
Introduction to PHP OOP
Introduction to PHP OOPIntroduction to PHP OOP
Introduction to PHP OOP
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
Php oop presentation
Php   oop presentationPhp   oop presentation
Php oop presentation
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
Intro to OOP PHP and Github
Intro to OOP PHP and GithubIntro to OOP PHP and Github
Intro to OOP PHP and Github
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
 
OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 

Similar to 09 Object Oriented Programming in PHP #burningkeyboards

Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in phpAashiq Kuchey
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHPRohan Sharma
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfObject_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfGammingWorld2
 
PHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptxPHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptxAtikur Rahman
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHPwahidullah mudaser
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2Mudasir Syed
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Alena Holligan
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classesKumar
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxShaownRoy1
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Alena Holligan
 
Object oriented php
Object oriented phpObject oriented php
Object oriented phpjwperry
 

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

UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in php
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Oops in php
Oops in phpOops in php
Oops in php
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
 
Introduction Php
Introduction PhpIntroduction Php
Introduction Php
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfObject_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdf
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
PHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptxPHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptx
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
 
Oops concept in php
Oops concept in phpOops concept in php
Oops concept in php
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
Lecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptxLecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptx
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
 
Object oriented php
Object oriented phpObject oriented php
Object oriented php
 

More from Denis Ristic

Magento Continuous Integration & Continuous Delivery @MM17HR
Magento Continuous Integration & Continuous Delivery @MM17HRMagento Continuous Integration & Continuous Delivery @MM17HR
Magento Continuous Integration & Continuous Delivery @MM17HRDenis Ristic
 
Continuous integration & Continuous Delivery @DeVz
Continuous integration & Continuous Delivery @DeVzContinuous integration & Continuous Delivery @DeVz
Continuous integration & Continuous Delivery @DeVzDenis Ristic
 
25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboards25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboardsDenis Ristic
 
24 Scrum #burningkeyboards
24 Scrum #burningkeyboards24 Scrum #burningkeyboards
24 Scrum #burningkeyboardsDenis Ristic
 
23 LAMP Stack #burningkeyboards
23 LAMP Stack #burningkeyboards23 LAMP Stack #burningkeyboards
23 LAMP Stack #burningkeyboardsDenis Ristic
 
22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboards22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboardsDenis Ristic
 
21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboards21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboardsDenis Ristic
 
20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboards20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboardsDenis Ristic
 
19 GitFlow #burningkeyboards
19 GitFlow #burningkeyboards19 GitFlow #burningkeyboards
19 GitFlow #burningkeyboardsDenis Ristic
 
18 Git #burningkeyboards
18 Git #burningkeyboards18 Git #burningkeyboards
18 Git #burningkeyboardsDenis Ristic
 
17 Linux Basics #burningkeyboards
17 Linux Basics #burningkeyboards17 Linux Basics #burningkeyboards
17 Linux Basics #burningkeyboardsDenis Ristic
 
16 MySQL Optimization #burningkeyboards
16 MySQL Optimization #burningkeyboards16 MySQL Optimization #burningkeyboards
16 MySQL Optimization #burningkeyboardsDenis Ristic
 
15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboardsDenis Ristic
 
14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboardsDenis Ristic
 
13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboards13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboardsDenis Ristic
 
12 Composer #burningkeyboards
12 Composer #burningkeyboards12 Composer #burningkeyboards
12 Composer #burningkeyboardsDenis Ristic
 
11 PHP Security #burningkeyboards
11 PHP Security #burningkeyboards11 PHP Security #burningkeyboards
11 PHP Security #burningkeyboardsDenis Ristic
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboardsDenis Ristic
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboardsDenis Ristic
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboardsDenis Ristic
 

More from Denis Ristic (20)

Magento Continuous Integration & Continuous Delivery @MM17HR
Magento Continuous Integration & Continuous Delivery @MM17HRMagento Continuous Integration & Continuous Delivery @MM17HR
Magento Continuous Integration & Continuous Delivery @MM17HR
 
Continuous integration & Continuous Delivery @DeVz
Continuous integration & Continuous Delivery @DeVzContinuous integration & Continuous Delivery @DeVz
Continuous integration & Continuous Delivery @DeVz
 
25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboards25 Intro to Symfony #burningkeyboards
25 Intro to Symfony #burningkeyboards
 
24 Scrum #burningkeyboards
24 Scrum #burningkeyboards24 Scrum #burningkeyboards
24 Scrum #burningkeyboards
 
23 LAMP Stack #burningkeyboards
23 LAMP Stack #burningkeyboards23 LAMP Stack #burningkeyboards
23 LAMP Stack #burningkeyboards
 
22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboards22 REST & JSON API Design #burningkeyboards
22 REST & JSON API Design #burningkeyboards
 
21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboards21 HTTP Protocol #burningkeyboards
21 HTTP Protocol #burningkeyboards
 
20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboards20 PHP Static Analysis and Documentation Generators #burningkeyboards
20 PHP Static Analysis and Documentation Generators #burningkeyboards
 
19 GitFlow #burningkeyboards
19 GitFlow #burningkeyboards19 GitFlow #burningkeyboards
19 GitFlow #burningkeyboards
 
18 Git #burningkeyboards
18 Git #burningkeyboards18 Git #burningkeyboards
18 Git #burningkeyboards
 
17 Linux Basics #burningkeyboards
17 Linux Basics #burningkeyboards17 Linux Basics #burningkeyboards
17 Linux Basics #burningkeyboards
 
16 MySQL Optimization #burningkeyboards
16 MySQL Optimization #burningkeyboards16 MySQL Optimization #burningkeyboards
16 MySQL Optimization #burningkeyboards
 
15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards
 
14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards
 
13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboards13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboards
 
12 Composer #burningkeyboards
12 Composer #burningkeyboards12 Composer #burningkeyboards
12 Composer #burningkeyboards
 
11 PHP Security #burningkeyboards
11 PHP Security #burningkeyboards11 PHP Security #burningkeyboards
11 PHP Security #burningkeyboards
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
 

Recently uploaded

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Recently uploaded (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 

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 <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
  • 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