SlideShare a Scribd company logo
Define
 Classes : Blue print for any project
 Object : An object is a specific instance of a
class
 Characteristics : the characteristics of a class
or object are known as its properties .
 Method : The behaviors of a class — that is,
the actions associated with the class — are
known as its methods .
Create a PHP class
<?php
class person {
}
?>
Add Data to Class
<?php
class person {
var $name;
}
?>
Add Function/Method to class
<?php
class person {
var $name;
function set_name($new_name) {
$this->name=$new_name;
}
function get_name() {
return $this->name;
}
}
?>
Include in Main file
<?php
include(“Class_lib.php”);
?>
Create Object
<?php
include(“Class_lib.php”);
$stefan=new person();
$jimmy=new person();
?>
Set Object Properties
<?php
include(“Class_lib.php”);
$stefan=new person();
$jimmy=new person();
$stefan->set_name("Stefan Mischook");
$jimmy->set_name("Nick Waddles");
?>
Accessing an Objects Data
<?php
include(“Class_lib.php”);
$stefan=new person();
$jimmy=new person();
$stefan->set_name("Stefan Mischook");
$jimmy->set_name("Nick Waddles");
echo "Stefan's full name: " . $stefan->get_name();
echo "Nick's full name: " . $jimmy->get_name();
?>
Don’t Access Property Directly
• Bad Example
<?php
include(“Class_lib.php”);
$stefan=new person();
$jimmy=new person();
$stefan->set_name("Stefan Mischook");
$jimmy->set_name("Nick Waddles");
echo "Stefan's full name: " . $stefan->name;
?>
Constructor
<?php
class person {
var $name;
function __construct($person) {
$this->name=$person
}
function set_name($new_name) {
$this->name=$new_name;
}
function get_name() {
return $this->name;
}
}
?>
<?php
include(“Class_lib.php”);
$stefan=new person("Stefan Mischook");
echo "Stefan's full name: " . $stefan->
get_name();
?>
Access Modifier
• Public properties can be accessed by any code, whether
that code is inside or outside the class. If a property is
declared public, its value can be read or changed from
anywhere in your script.
• Private properties of a class can be accessed only by
code inside the class. So if you create a property that ’ s
declared private, only methods inside the same class
can access its contents. (If you attempt to access the
property outside the class, PHP generates a fatal error.)
• Protected properties are a bit like private properties in
that they can ’ t be accessed by code outside the class,
but there ’ s one subtle difference: any class that
inherits from the class can also access the properties.
Reusing the code : Inheritance
<?php
class employee extends person {
//Extends is the keysword used for inheritance
function __construct($ename)
{
$this->name=$ename;
}
}
?>
<?php
include(“Class_lib.php”);
$jimmy=new employee(“Johnes fingers");
echo “jimmy's full name: " . $jimmy->
get_name();
?>
Overriding Method
<?php
class employee extends person {
//Extends is the keysword used for inheritance
function __construct($ename)
{
$this->name=$ename;
}
}
protected function set_name($new_name) {
if ($new_name == "Stefan Lamp") {
$this->name = $new_name;!
}?>
Working with __get() __set() __call()
Method
• PHP allows you to create three “ magic ” methods
that you can use to intercept property and
method accesses:
• _get() is called whenever the calling code
attempts to read an invisible property of the
object
• _set() is called whenever the calling code
attempts to write to an invisible property of the
object
• _call() is called whenever the calling code
attempts to call an invisible method of the object
What is meant by “ invisible ” ?
• In this context, invisible means that the
property or method isn ’ t visible to the calling
code. Usually this means that the property or
method simply doesn ’ t exist in the class, but
it can also mean that the property or method
is either private or protected, and hence isn ’ t
accessible to code outside the class.
Example of __get()
class Car {
public function __get( $propertyName ) {
echo “The value of ‘$propertyName’ was requested < br / > ”;
return “blue”;
}
}
$car = new Car();
$x = $car- > color; // Displays “The value of ‘color’ was
requested”
echo “The car’s color is $x < br / > ”; // Displays “The car’s
color is blue”
• Similarly, to catch an attempt to set an
invisible property to a value, use _set() .
• Your _set() method needs two parameters:
the property name and the value to set it to. It
does not need to return a value:
public function __set( $propertyName,
$propertyValue ) {
//Do what ever u want to do here
}
Example
<?php
class Car {
private $_extradata=array();
public function __set($propertyName, $propertyValue ) {
$this-> _extraData[$propertyName] = $propertyValue;
}
}
$car = new Car;
$car->color="red";
print_r($car);
?>
• Just as you can use _get() and _set() to handle reading and
writing nonexistent properties.
• you can also use _call() to handle calls to nonexistent
methods of a class.
• Just create a method named _call() in your class that
accepts the nonexistent method name as a string, and any
arguments passed to the nonexistent method as an array.
• The method should then return a value (if any) back to the
calling code:
public function __call( $methodName, $arguments ) {
// (do stuff here)
return $returnVal;
}
Example
<?php
class Car {
public function __call($MethodName, $argument) {
echo "The value of '$MethodName' was requested < br
/ > ";
return $argument[0];
}
}
$car = new Car;
$x = $car-> color("red");
echo "The car's color is $x < br / > ";
?>
Other Magic Method
• _isset() is called whenever the calling code
attempts to call PHP ’ s isset() function on an
invisible property. It takes one argument —
the property name — and should return true
if the property is deemed to be “ set, ” and
false otherwise:
Example
class MyClass {
public function __isset( $propertyName ) {
// All properties beginning with “test” are “set”
return ( substr( $propertyName, 0, 4 ) == “test” ) ? true : false;
}
}
$testObject = new MyClass;
echo isset( $testObject- > banana ) . “ < br / > ”; // Displays “”
(false)
echo isset( $testObject- > testBanana ) . “ < br / > ”; //
Displays “1” (true)
• __unset() is called when the calling code
attempts to delete an invisible property with
PHP ’ s unset() function. It shouldn ’ t return a
value, but should do whatever is necessary to
“ unset ” the property (if applicable):
Example
class MyClass {
public function __unset( $propertyName ) {
echo “Unsetting property ‘$propertyName’ < br / >
”;
}
}
$testObject = new MyClass;
unset( $testObject- > banana ); // Displays
“Unsetting property ‘banana’”
• __callStatic() works like _call() , except that it is called whenever an
attempt is made to call an invisible static method. For example:
class MyClass {
public static function __callStatic( $methodName, $arguments ) {
echo “Static method ‘$methodName’ called with the arguments: < br /
> ”;
foreach ( $arguments as $arg ) {
echo “$arg < br / > ”;
}
}
}
MyClass::randomMethod( “apple”, “peach”, “strawberry” );
Storing Object as a String
• Objects that you create in PHP are stored as
binary data in memory. Although you can pass
objects around using PHP variables, functions,
and methods, sometimes its useful to be able to
pass objects to other applications, or via fields in
Web forms, for example.
• PHP provides two functions to help you with this:
– serialize() converts an object — properties, methods,
and all — into a string of text
– unserialize() takes a string created by serialize() and
turns it back into a usable object
Example
class Person {
public $age;
}
$harry = new Person();
$harry- > age = 28;
$harryString = serialize( $harry );
echo “Harry is now serialized in the following string:
‘$harryString’ < br / > ”;
echo “Converting ‘$harryString’ back to an object... < br / > ”;
$obj = unserialize( $harryString );
echo “Harry’s age is: $obj- > age < br / > ”;
• What ’ s more, when you serialize an object, PHP attempts to call a
method with the name _sleep() inside the object. You can use this
method to do anything that ’ s required before the object is
serialized.
• Similarly, you can create a _wakeup() method that is called when
the object is unserialized.
• _sleep() is useful for cleaning up an object prior to serializing it, in
the same way that you might clean up in a destructor method. For
example, you might need to close database handles, files, and so
on.
• In addition, _sleep() has another trick up its sleeve. PHP expects
your _sleep() method to return an array of names of properties to
preserve in the serialized string. You can use this fact to limit the
number of properties stored in the string — very useful if your
object contains a lot of properties that you don ’ t need to store.
Example
class User {
public $username;
public $password;
public $loginsToday;
public function __sleep() {
// (Clean up; close database handles, etc)
return array_keys( get_object_vars( $this ) );
}
}
Example
class User {
public function __wakeup() {
echo “Yawn... what’s for breakfast? < br / > ”;
}
}
$user = new User;
$userString = serialize( $user );
$obj = unserialize( $userString );

More Related Content

PPTX
Data structure and its types
PPTX
Stack & Queue using Linked List in Data Structure
PDF
Estrutura de Dados Apoio (Tabela Hash)
PPTX
Linked list
PPTX
Ddl &amp; dml commands
PPTX
Normal forms
PPTX
Queue and its operations
PPTX
Cascading style sheets (CSS-Web Technology)
Data structure and its types
Stack & Queue using Linked List in Data Structure
Estrutura de Dados Apoio (Tabela Hash)
Linked list
Ddl &amp; dml commands
Normal forms
Queue and its operations
Cascading style sheets (CSS-Web Technology)

What's hot (20)

PPTX
Binary tree and operations
PPT
PPTX
Id and class selector
PPTX
PHP Powerpoint -- Teach PHP with this
PPTX
basic structure of SQL FINAL.pptx
PDF
Data manipulation language
PDF
Python Orientação a Objeto
PPTX
08-Iterators-and-Generators.pptx
PPT
SEARCHING AND SORTING ALGORITHMS
PPTX
php basics
PDF
SQL Queries - DDL Commands
PPTX
Flex box
PPT
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PPT
Data Structures- Part7 linked lists
PPT
MYSQL - PHP Database Connectivity
PPTX
Web html table tags
PPTX
Java I/O and Object Serialization
PPSX
Collections - Lists, Sets
PDF
PPTX
Sql Constraints
Binary tree and operations
Id and class selector
PHP Powerpoint -- Teach PHP with this
basic structure of SQL FINAL.pptx
Data manipulation language
Python Orientação a Objeto
08-Iterators-and-Generators.pptx
SEARCHING AND SORTING ALGORITHMS
php basics
SQL Queries - DDL Commands
Flex box
PHP - DataType,Variable,Constant,Operators,Array,Include and require
Data Structures- Part7 linked lists
MYSQL - PHP Database Connectivity
Web html table tags
Java I/O and Object Serialization
Collections - Lists, Sets
Sql Constraints
Ad

Similar to OOP in PHP.pptx (20)

PPT
Advanced php
PPTX
PPTX
Ch8(oop)
PDF
Object::Trampoline: Follow the bouncing object.
PPT
Synapseindia object oriented programming in php
PDF
Demystifying Object-Oriented Programming - Lone Star PHP
PPTX
Lecture9_OOPHP_SPring2023.pptx
PPTX
php2.pptx
ODP
Perl Teach-In (part 2)
KEY
Can't Miss Features of PHP 5.3 and 5.4
PDF
50 Laravel Tricks in 50 Minutes
PDF
laravel tricks in 50minutes
PDF
PHP 5.3 Overview
PDF
SPL: The Missing Link in Development
PDF
Demystifying Object-Oriented Programming - ZendCon 2016
PPT
Php object orientation and classes
PDF
Object Oriented Programming with PHP 5 - More OOP
PPTX
FFW Gabrovo PMG - PHP OOP Part 3
PDF
Object Trampoline: Why having not the object you want is what you need.
Advanced php
Ch8(oop)
Object::Trampoline: Follow the bouncing object.
Synapseindia object oriented programming in php
Demystifying Object-Oriented Programming - Lone Star PHP
Lecture9_OOPHP_SPring2023.pptx
php2.pptx
Perl Teach-In (part 2)
Can't Miss Features of PHP 5.3 and 5.4
50 Laravel Tricks in 50 Minutes
laravel tricks in 50minutes
PHP 5.3 Overview
SPL: The Missing Link in Development
Demystifying Object-Oriented Programming - ZendCon 2016
Php object orientation and classes
Object Oriented Programming with PHP 5 - More OOP
FFW Gabrovo PMG - PHP OOP Part 3
Object Trampoline: Why having not the object you want is what you need.
Ad

More from switipatel4 (8)

PPTX
DIGITAL_COMMUNITY PPT ABOUT ONLINE SOCIAL LIFE
PPTX
Coding_Guidelines for the better and maintainable coding
PPT
PPT for Advanced Relational Database Management System
PPT
Expert System in artificial intelligence
PDF
Mobile application and android with java questions
PPTX
Php image functions.pptx
PPT
E-Mail.ppt
PPTX
Software ppt
DIGITAL_COMMUNITY PPT ABOUT ONLINE SOCIAL LIFE
Coding_Guidelines for the better and maintainable coding
PPT for Advanced Relational Database Management System
Expert System in artificial intelligence
Mobile application and android with java questions
Php image functions.pptx
E-Mail.ppt
Software ppt

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Cloud computing and distributed systems.
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Empathic Computing: Creating Shared Understanding
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Electronic commerce courselecture one. Pdf
PPTX
A Presentation on Artificial Intelligence
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPT
Teaching material agriculture food technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Digital-Transformation-Roadmap-for-Companies.pptx
Cloud computing and distributed systems.
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
MYSQL Presentation for SQL database connectivity
Empathic Computing: Creating Shared Understanding
Dropbox Q2 2025 Financial Results & Investor Presentation
Electronic commerce courselecture one. Pdf
A Presentation on Artificial Intelligence
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Advanced methodologies resolving dimensionality complications for autism neur...
Teaching material agriculture food technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Understanding_Digital_Forensics_Presentation.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Mobile App Security Testing_ A Comprehensive Guide.pdf
Unlocking AI with Model Context Protocol (MCP)
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
The Rise and Fall of 3GPP – Time for a Sabbatical?

OOP in PHP.pptx

  • 1. Define  Classes : Blue print for any project  Object : An object is a specific instance of a class  Characteristics : the characteristics of a class or object are known as its properties .  Method : The behaviors of a class — that is, the actions associated with the class — are known as its methods .
  • 2. Create a PHP class <?php class person { } ?>
  • 3. Add Data to Class <?php class person { var $name; } ?>
  • 4. Add Function/Method to class <?php class person { var $name; function set_name($new_name) { $this->name=$new_name; } function get_name() { return $this->name; } } ?>
  • 5. Include in Main file <?php include(“Class_lib.php”); ?>
  • 7. Set Object Properties <?php include(“Class_lib.php”); $stefan=new person(); $jimmy=new person(); $stefan->set_name("Stefan Mischook"); $jimmy->set_name("Nick Waddles"); ?>
  • 8. Accessing an Objects Data <?php include(“Class_lib.php”); $stefan=new person(); $jimmy=new person(); $stefan->set_name("Stefan Mischook"); $jimmy->set_name("Nick Waddles"); echo "Stefan's full name: " . $stefan->get_name(); echo "Nick's full name: " . $jimmy->get_name(); ?>
  • 9. Don’t Access Property Directly • Bad Example <?php include(“Class_lib.php”); $stefan=new person(); $jimmy=new person(); $stefan->set_name("Stefan Mischook"); $jimmy->set_name("Nick Waddles"); echo "Stefan's full name: " . $stefan->name; ?>
  • 10. Constructor <?php class person { var $name; function __construct($person) { $this->name=$person } function set_name($new_name) { $this->name=$new_name; } function get_name() { return $this->name; } } ?>
  • 11. <?php include(“Class_lib.php”); $stefan=new person("Stefan Mischook"); echo "Stefan's full name: " . $stefan-> get_name(); ?>
  • 12. Access Modifier • Public properties can be accessed by any code, whether that code is inside or outside the class. If a property is declared public, its value can be read or changed from anywhere in your script. • Private properties of a class can be accessed only by code inside the class. So if you create a property that ’ s declared private, only methods inside the same class can access its contents. (If you attempt to access the property outside the class, PHP generates a fatal error.) • Protected properties are a bit like private properties in that they can ’ t be accessed by code outside the class, but there ’ s one subtle difference: any class that inherits from the class can also access the properties.
  • 13. Reusing the code : Inheritance <?php class employee extends person { //Extends is the keysword used for inheritance function __construct($ename) { $this->name=$ename; } } ?>
  • 15. Overriding Method <?php class employee extends person { //Extends is the keysword used for inheritance function __construct($ename) { $this->name=$ename; } } protected function set_name($new_name) { if ($new_name == "Stefan Lamp") { $this->name = $new_name;! }?>
  • 16. Working with __get() __set() __call() Method • PHP allows you to create three “ magic ” methods that you can use to intercept property and method accesses: • _get() is called whenever the calling code attempts to read an invisible property of the object • _set() is called whenever the calling code attempts to write to an invisible property of the object • _call() is called whenever the calling code attempts to call an invisible method of the object
  • 17. What is meant by “ invisible ” ? • In this context, invisible means that the property or method isn ’ t visible to the calling code. Usually this means that the property or method simply doesn ’ t exist in the class, but it can also mean that the property or method is either private or protected, and hence isn ’ t accessible to code outside the class.
  • 18. Example of __get() class Car { public function __get( $propertyName ) { echo “The value of ‘$propertyName’ was requested < br / > ”; return “blue”; } } $car = new Car(); $x = $car- > color; // Displays “The value of ‘color’ was requested” echo “The car’s color is $x < br / > ”; // Displays “The car’s color is blue”
  • 19. • Similarly, to catch an attempt to set an invisible property to a value, use _set() . • Your _set() method needs two parameters: the property name and the value to set it to. It does not need to return a value: public function __set( $propertyName, $propertyValue ) { //Do what ever u want to do here }
  • 20. Example <?php class Car { private $_extradata=array(); public function __set($propertyName, $propertyValue ) { $this-> _extraData[$propertyName] = $propertyValue; } } $car = new Car; $car->color="red"; print_r($car); ?>
  • 21. • Just as you can use _get() and _set() to handle reading and writing nonexistent properties. • you can also use _call() to handle calls to nonexistent methods of a class. • Just create a method named _call() in your class that accepts the nonexistent method name as a string, and any arguments passed to the nonexistent method as an array. • The method should then return a value (if any) back to the calling code: public function __call( $methodName, $arguments ) { // (do stuff here) return $returnVal; }
  • 22. Example <?php class Car { public function __call($MethodName, $argument) { echo "The value of '$MethodName' was requested < br / > "; return $argument[0]; } } $car = new Car; $x = $car-> color("red"); echo "The car's color is $x < br / > "; ?>
  • 23. Other Magic Method • _isset() is called whenever the calling code attempts to call PHP ’ s isset() function on an invisible property. It takes one argument — the property name — and should return true if the property is deemed to be “ set, ” and false otherwise:
  • 24. Example class MyClass { public function __isset( $propertyName ) { // All properties beginning with “test” are “set” return ( substr( $propertyName, 0, 4 ) == “test” ) ? true : false; } } $testObject = new MyClass; echo isset( $testObject- > banana ) . “ < br / > ”; // Displays “” (false) echo isset( $testObject- > testBanana ) . “ < br / > ”; // Displays “1” (true)
  • 25. • __unset() is called when the calling code attempts to delete an invisible property with PHP ’ s unset() function. It shouldn ’ t return a value, but should do whatever is necessary to “ unset ” the property (if applicable):
  • 26. Example class MyClass { public function __unset( $propertyName ) { echo “Unsetting property ‘$propertyName’ < br / > ”; } } $testObject = new MyClass; unset( $testObject- > banana ); // Displays “Unsetting property ‘banana’”
  • 27. • __callStatic() works like _call() , except that it is called whenever an attempt is made to call an invisible static method. For example: class MyClass { public static function __callStatic( $methodName, $arguments ) { echo “Static method ‘$methodName’ called with the arguments: < br / > ”; foreach ( $arguments as $arg ) { echo “$arg < br / > ”; } } } MyClass::randomMethod( “apple”, “peach”, “strawberry” );
  • 28. Storing Object as a String • Objects that you create in PHP are stored as binary data in memory. Although you can pass objects around using PHP variables, functions, and methods, sometimes its useful to be able to pass objects to other applications, or via fields in Web forms, for example. • PHP provides two functions to help you with this: – serialize() converts an object — properties, methods, and all — into a string of text – unserialize() takes a string created by serialize() and turns it back into a usable object
  • 29. Example class Person { public $age; } $harry = new Person(); $harry- > age = 28; $harryString = serialize( $harry ); echo “Harry is now serialized in the following string: ‘$harryString’ < br / > ”; echo “Converting ‘$harryString’ back to an object... < br / > ”; $obj = unserialize( $harryString ); echo “Harry’s age is: $obj- > age < br / > ”;
  • 30. • What ’ s more, when you serialize an object, PHP attempts to call a method with the name _sleep() inside the object. You can use this method to do anything that ’ s required before the object is serialized. • Similarly, you can create a _wakeup() method that is called when the object is unserialized. • _sleep() is useful for cleaning up an object prior to serializing it, in the same way that you might clean up in a destructor method. For example, you might need to close database handles, files, and so on. • In addition, _sleep() has another trick up its sleeve. PHP expects your _sleep() method to return an array of names of properties to preserve in the serialized string. You can use this fact to limit the number of properties stored in the string — very useful if your object contains a lot of properties that you don ’ t need to store.
  • 31. Example class User { public $username; public $password; public $loginsToday; public function __sleep() { // (Clean up; close database handles, etc) return array_keys( get_object_vars( $this ) ); } }
  • 32. Example class User { public function __wakeup() { echo “Yawn... what’s for breakfast? < br / > ”; } } $user = new User; $userString = serialize( $user ); $obj = unserialize( $userString );