SlideShare a Scribd company logo
1 of 54
PHP 5 Magic Functions Front Range PHP Users Group http://frontrangephp.org/ February 10, 2010
PHP 5 Magic Functions All functions start with __ PHP reserves all function names starting with __ Don’t define them unless you want the magic functionality
Magic Methods in this Presentation __construct() __destruct() __toString() __get() __set() __isset() __unset() __call() __clone __set_state()
Magic Methods briefly covered __callStatic() __sleep() __wakeup() __invoke() __autoload()
New to PHP 5 Magic functions (in general) allow you to define class functionality without needing to duplicate code I say in general since some of them don’t really seem to follow that definition and I didn’t find a definition that covers them all.
__construct() If you’ve done any OOP in PHP5, you’ve probably run into this method. Used to initialize an object. Best practices say to make sure you don’t do work in the constructor. Just assign values … and remember Dependency Injection (coming up next)
__construct() Constructor is setting values, but not doing work
__construct() Doing work in constructors makes it harder to reuse the class.
__construct() If you don’t provide a constructor method, and extend a class, the parent constructor will be called automatically. If you do provide a constructor, and want the parent constructor called, you must called parent::__construct()
__construct() By making the constructor inaccessible, you can prevent external instantiation. For example, implementing the singleton pattern, we don’t want external instantiation since we cannot control how many objects are created.
__destruct() __destruct() is called when  all references to an object are removed object is explicitly destroyed shutdown sequence is initiated
__destruct() Parent destructors must be called explicitly if destructor is provided
__destruct() You could use this method to ensure an object logs itself.
__destruct() The destructor is called even if a script exits due to a call to exit() However, if you call exit() in a destructor, the other destructors will be skipped. Throwing an exception in the destructor is a fatal error.
__toString() Called whenever you try to use an object in a string context
__toString()
__toString() You can invoke via echo, print, *printf Cast to string $var = (string)$obj;
__toString() __toString() cannot throw an exception – results in a fatal error If you call functions or methods in your __toString() that can throw an exception, make sure you handle it within the __toString()  method
__get() Called when code tries to access non-accessible properties
__get() Non-accessible can mean either the property is not defined or that it is not public If it’s not defined, then __get() will be called from both inside and outside of the class context
__get()
__get()
__get() Classes don’t even have to have properties
__get() You could even use it to process values…
__set() Called when code tries to set a property that is not accessible. Not accessible can mean not defined or not public
__set()
__set() If __set() is used to set a property that doesn’t exist, the new property will be public. If it is used on a property that is not public, the accessibility will not change
__set() Use it to validate values as they are passed in
__set() If you want only the values you defined to be used in a class, set that behavior in __set().
__isset() Called when isset() is called on an inaccessible property If you’re using __set() and __get(), not defining __isset() can lead to some really weird errors.
__isset()
__isset() How can this be? You can retrieve the value, but it’s not set? Must define  __isset()
__unset() Called when code tries to unset a non-accessible value. Without __unset()
__unset() With __unset()
__call() Called when a method is called that is not accessible.
__call() Use it to extend a class and make everything public…
__call() Yes, I didn’t extend anything in that example, but the principle is the same
__call() Virtual Getters and Setters
__call() All sorts of other uses for __call()
__clone() Used if custom clone() behavior is needed If clone() is called on an object that contains other objects, both the clone and the original contain the same objects. Define __clone() to define what happens when an object is cloned
__clone() Default Clone behavior Using === to show they are the same
__clone() Now with custom __clone()
__clone() In the previous example we are comparing the objects Even if the number value is the same, there are still two different objects
__set_state() Used to set the state of an object when var_export code is used.
__set_state() var_export() creates runnable PHP code. So what happens when we run it?
__set_state() So let’s define it
__set_state() Why the differences? stdClass doesn’t have a __set_state() Since $val is protected, I need a setter. Plus it shows how to deal with non-public stuff
Brief Look at other magic methods You’ve already seen 48 slides, and chances are it’s getting close to an hour… So here’s a quick overview of a few more of the magic methods
__callStatic() New in PHP 5.3 Very similar to __call() Intended for when a method is called in a static context (inaccessible method) SomeClass::protectedStaticMethod();
__sleep() Called when an object is serialized with PHP’s serialize. Can be used to shutdown and remove resources (like database connections) which cannot be serialized
__wakeup() Called when an object is unserialized. Can be used to re-establish connections and re-initialize resources ie, reconnect to the database
__invoke() New in PHP 5.3 Allows you to treat an object like a function
__autoload() Everyone using PHP 5 should be using this, or at least some form of autoloading. Allows you to automatically load PHP files when they are needed. No more need for require_once or include_once in your scripts
Q & A	 Any questions?

More Related Content

What's hot

Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
Adan Hubahib
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Christian Schneider
 
MySQL源码分析.01.代码结构与基本流程
MySQL源码分析.01.代码结构与基本流程MySQL源码分析.01.代码结构与基本流程
MySQL源码分析.01.代码结构与基本流程
Lixun Peng
 

What's hot (20)

SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Presentation on c programing satcture
Presentation on c programing satcture Presentation on c programing satcture
Presentation on c programing satcture
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
 
Access specifiers (Public Private Protected) C++
Access specifiers (Public Private  Protected) C++Access specifiers (Public Private  Protected) C++
Access specifiers (Public Private Protected) C++
 
11 constructors in derived classes
11 constructors in derived classes11 constructors in derived classes
11 constructors in derived classes
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
11. java methods
11. java methods11. java methods
11. java methods
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
 
MySQL源码分析.01.代码结构与基本流程
MySQL源码分析.01.代码结构与基本流程MySQL源码分析.01.代码结构与基本流程
MySQL源码分析.01.代码结构与基本流程
 
JavaScript sunumu
JavaScript sunumuJavaScript sunumu
JavaScript sunumu
 
Methods in java
Methods in javaMethods in java
Methods in java
 
Reflection in C#
Reflection in C#Reflection in C#
Reflection in C#
 
JDBC
JDBCJDBC
JDBC
 

Similar to PHP 5 Magic Methods

OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
Array with Iterator. Java styleImplement an array data structure a.pdf
Array with Iterator. Java styleImplement an array data structure a.pdfArray with Iterator. Java styleImplement an array data structure a.pdf
Array with Iterator. Java styleImplement an array data structure a.pdf
fcaindore
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 

Similar to PHP 5 Magic Methods (20)

OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
Collections
CollectionsCollections
Collections
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Array with Iterator. Java styleImplement an array data structure a.pdf
Array with Iterator. Java styleImplement an array data structure a.pdfArray with Iterator. Java styleImplement an array data structure a.pdf
Array with Iterator. Java styleImplement an array data structure a.pdf
 
Oops
OopsOops
Oops
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Only oop
Only oopOnly oop
Only oop
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
 
Magic function in PHP
Magic function in PHPMagic function in PHP
Magic function in PHP
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Defining method in JavaScript object.pptx
Defining method in JavaScript object.pptxDefining method in JavaScript object.pptx
Defining method in JavaScript object.pptx
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming Rails
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 

More from David Stockton

Increasing code quality with code reviews (poetry version)
Increasing code quality with code reviews (poetry version)Increasing code quality with code reviews (poetry version)
Increasing code quality with code reviews (poetry version)
David Stockton
 

More from David Stockton (19)

Phone calls and sms from php
Phone calls and sms from phpPhone calls and sms from php
Phone calls and sms from php
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of Transduction
 
Using queues and offline processing to help speed up your application
Using queues and offline processing to help speed up your applicationUsing queues and offline processing to help speed up your application
Using queues and offline processing to help speed up your application
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
Building APIs with Apigilty and Zend Framework 2
Building APIs with Apigilty and Zend Framework 2Building APIs with Apigilty and Zend Framework 2
Building APIs with Apigilty and Zend Framework 2
 
API All the Things!
API All the Things!API All the Things!
API All the Things!
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
Hacking sites for fun and profit
Hacking sites for fun and profitHacking sites for fun and profit
Hacking sites for fun and profit
 
Beginning OOP in PHP
Beginning OOP in PHPBeginning OOP in PHP
Beginning OOP in PHP
 
Common design patterns in php
Common design patterns in phpCommon design patterns in php
Common design patterns in php
 
Intermediate oop in php
Intermediate oop in phpIntermediate oop in php
Intermediate oop in php
 
Grokking regex
Grokking regexGrokking regex
Grokking regex
 
Hacking sites for fun and profit
Hacking sites for fun and profitHacking sites for fun and profit
Hacking sites for fun and profit
 
Hacking sites for fun and profit
Hacking sites for fun and profitHacking sites for fun and profit
Hacking sites for fun and profit
 
Increasing code quality with code reviews (poetry version)
Increasing code quality with code reviews (poetry version)Increasing code quality with code reviews (poetry version)
Increasing code quality with code reviews (poetry version)
 
Tame Your Build And Deployment Process With Hudson, PHPUnit, and SSH
Tame Your Build And Deployment Process With Hudson, PHPUnit, and SSHTame Your Build And Deployment Process With Hudson, PHPUnit, and SSH
Tame Your Build And Deployment Process With Hudson, PHPUnit, and SSH
 
Mercurial Distributed Version Control
Mercurial Distributed Version ControlMercurial Distributed Version Control
Mercurial Distributed Version Control
 
Regular expressions and php
Regular expressions and phpRegular expressions and php
Regular expressions and php
 
FireBug And FirePHP
FireBug And FirePHPFireBug And FirePHP
FireBug And FirePHP
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
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...
 
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...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

PHP 5 Magic Methods

  • 1. PHP 5 Magic Functions Front Range PHP Users Group http://frontrangephp.org/ February 10, 2010
  • 2. PHP 5 Magic Functions All functions start with __ PHP reserves all function names starting with __ Don’t define them unless you want the magic functionality
  • 3. Magic Methods in this Presentation __construct() __destruct() __toString() __get() __set() __isset() __unset() __call() __clone __set_state()
  • 4. Magic Methods briefly covered __callStatic() __sleep() __wakeup() __invoke() __autoload()
  • 5. New to PHP 5 Magic functions (in general) allow you to define class functionality without needing to duplicate code I say in general since some of them don’t really seem to follow that definition and I didn’t find a definition that covers them all.
  • 6. __construct() If you’ve done any OOP in PHP5, you’ve probably run into this method. Used to initialize an object. Best practices say to make sure you don’t do work in the constructor. Just assign values … and remember Dependency Injection (coming up next)
  • 7. __construct() Constructor is setting values, but not doing work
  • 8. __construct() Doing work in constructors makes it harder to reuse the class.
  • 9. __construct() If you don’t provide a constructor method, and extend a class, the parent constructor will be called automatically. If you do provide a constructor, and want the parent constructor called, you must called parent::__construct()
  • 10. __construct() By making the constructor inaccessible, you can prevent external instantiation. For example, implementing the singleton pattern, we don’t want external instantiation since we cannot control how many objects are created.
  • 11. __destruct() __destruct() is called when all references to an object are removed object is explicitly destroyed shutdown sequence is initiated
  • 12. __destruct() Parent destructors must be called explicitly if destructor is provided
  • 13. __destruct() You could use this method to ensure an object logs itself.
  • 14. __destruct() The destructor is called even if a script exits due to a call to exit() However, if you call exit() in a destructor, the other destructors will be skipped. Throwing an exception in the destructor is a fatal error.
  • 15. __toString() Called whenever you try to use an object in a string context
  • 17. __toString() You can invoke via echo, print, *printf Cast to string $var = (string)$obj;
  • 18. __toString() __toString() cannot throw an exception – results in a fatal error If you call functions or methods in your __toString() that can throw an exception, make sure you handle it within the __toString() method
  • 19. __get() Called when code tries to access non-accessible properties
  • 20. __get() Non-accessible can mean either the property is not defined or that it is not public If it’s not defined, then __get() will be called from both inside and outside of the class context
  • 23. __get() Classes don’t even have to have properties
  • 24. __get() You could even use it to process values…
  • 25. __set() Called when code tries to set a property that is not accessible. Not accessible can mean not defined or not public
  • 27. __set() If __set() is used to set a property that doesn’t exist, the new property will be public. If it is used on a property that is not public, the accessibility will not change
  • 28. __set() Use it to validate values as they are passed in
  • 29. __set() If you want only the values you defined to be used in a class, set that behavior in __set().
  • 30. __isset() Called when isset() is called on an inaccessible property If you’re using __set() and __get(), not defining __isset() can lead to some really weird errors.
  • 32. __isset() How can this be? You can retrieve the value, but it’s not set? Must define __isset()
  • 33. __unset() Called when code tries to unset a non-accessible value. Without __unset()
  • 35. __call() Called when a method is called that is not accessible.
  • 36. __call() Use it to extend a class and make everything public…
  • 37. __call() Yes, I didn’t extend anything in that example, but the principle is the same
  • 39. __call() All sorts of other uses for __call()
  • 40. __clone() Used if custom clone() behavior is needed If clone() is called on an object that contains other objects, both the clone and the original contain the same objects. Define __clone() to define what happens when an object is cloned
  • 41. __clone() Default Clone behavior Using === to show they are the same
  • 42. __clone() Now with custom __clone()
  • 43. __clone() In the previous example we are comparing the objects Even if the number value is the same, there are still two different objects
  • 44. __set_state() Used to set the state of an object when var_export code is used.
  • 45. __set_state() var_export() creates runnable PHP code. So what happens when we run it?
  • 47. __set_state() Why the differences? stdClass doesn’t have a __set_state() Since $val is protected, I need a setter. Plus it shows how to deal with non-public stuff
  • 48. Brief Look at other magic methods You’ve already seen 48 slides, and chances are it’s getting close to an hour… So here’s a quick overview of a few more of the magic methods
  • 49. __callStatic() New in PHP 5.3 Very similar to __call() Intended for when a method is called in a static context (inaccessible method) SomeClass::protectedStaticMethod();
  • 50. __sleep() Called when an object is serialized with PHP’s serialize. Can be used to shutdown and remove resources (like database connections) which cannot be serialized
  • 51. __wakeup() Called when an object is unserialized. Can be used to re-establish connections and re-initialize resources ie, reconnect to the database
  • 52. __invoke() New in PHP 5.3 Allows you to treat an object like a function
  • 53. __autoload() Everyone using PHP 5 should be using this, or at least some form of autoloading. Allows you to automatically load PHP files when they are needed. No more need for require_once or include_once in your scripts
  • 54. Q & A Any questions?