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

PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
jsmith92
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
Kumar
 
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
Wildan Maulana
 

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

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 

Recently uploaded (20)

Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Buy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxBuy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptx
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
The UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, OcadoThe UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, Ocado
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
Buy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdfBuy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdf
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 

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