SlideShare a Scribd company logo
1 of 32
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

Similar to OOP in PHP.pptx

Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)Dave Cross
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Jeff Carouth
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classesKumar
 
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
 
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 Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Workhorse Computing
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHPwahidullah mudaser
 
Lecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptxLecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptxDavidLazar17
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboardsDenis Ristic
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 

Similar to OOP in PHP.pptx (20)

Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
 
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
 
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
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
PHP OOP
PHP OOPPHP OOP
PHP OOP
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 
Oops concept in php
Oops concept in phpOops concept in php
Oops concept in php
 
Perl object ?
Perl object ?Perl object ?
Perl object ?
 
Lecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptxLecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptx
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 

Recently uploaded

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Recently uploaded (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

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 );