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

Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
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
 
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
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
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
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
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
 
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
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
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
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 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 );