PHP 5 Magic Methods

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

More Related Content

What's hot

JUnit 5JUnit 5
JUnit 5Scott Leberknight
4.4K views59 slides
Clean codeClean code
Clean codeArturo Herrero
69.9K views88 slides
Oops concepts in phpOops concepts in php
Oops concepts in phpCPD INDIA
3.6K views44 slides
Clean CodeClean Code
Clean CodeDmytro Turskyi
215 views36 slides

What's hot(20)

JUnit 5JUnit 5
JUnit 5
Scott Leberknight4.4K views
Clean codeClean code
Clean code
Arturo Herrero69.9K views
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Stoyan Stefanov4K views
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA3.6K views
Clean CodeClean Code
Clean Code
Dmytro Turskyi215 views
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
Mario Sangiorgio15.6K views
Chapitre 2:  String en JavaChapitre 2:  String en Java
Chapitre 2: String en Java
Aziz Darouichi858 views
Functions in c++Functions in c++
Functions in c++
Rokonuzzaman Rony1.3K views
Clean codeClean code
Clean code
ifnu bima478 views
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
Exception handling in JavaException handling in Java
Exception handling in Java
Abhishek Pachisia9.8K views
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
Geshan Manandhar2.7K views
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar4.7K views
Standard template libraryStandard template library
Standard template library
Jancypriya M227 views
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
Francesco Casalegno4K views
Cours javascript v1Cours javascript v1
Cours javascript v1
TheBest Icanbe2.7K views
Groovy AST TransformationsGroovy AST Transformations
Groovy AST Transformations
hendersk3.9K views
Clean codeClean code
Clean code
Alvaro García Loaisa5.4K views

Similar to PHP 5 Magic Methods

OOPS IN PHP.pptxrani marri
12 views39 slides
178 views34 slides
Ruby basicsRuby basics
Ruby basicsAditya Tiwari
1.9K views40 slides
OopsSomdatta Kumar
174 views11 slides
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptxswitipatel4
6 views32 slides

Similar to PHP 5 Magic Methods(20)

rani marri12 views
sagsharma178 views
Ruby basicsRuby basics
Ruby basics
Aditya Tiwari1.9K views
Somdatta Kumar174 views
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
switipatel46 views
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
Ying Zhang6.9K views
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
Leonid Maslov281 views
Only oopOnly oop
Only oop
anitarooge33 views
Grails unit testingGrails unit testing
Grails unit testing
pleeps4.1K views
Python MetaclassesPython Metaclasses
Python Metaclasses
Nikunj Parekh432 views
Magic function in PHPMagic function in PHP
Magic function in PHP
EngrHasanuzzamanSumo4 views
Object oriented conceptsObject oriented concepts
Object oriented concepts
Gousalya Ramachandran22 views
Metaprogramming RailsMetaprogramming Rails
Metaprogramming Rails
Justus Eapen1.5K views
Nikunj Parekh317 views
Jist of JavaJist of Java
Jist of Java
Nikunj Parekh244 views

More from David Stockton(19)

Phone calls and sms from phpPhone calls and sms from php
Phone calls and sms from php
David Stockton667 views
The Art of TransductionThe Art of Transduction
The Art of Transduction
David Stockton588 views
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
David Stockton1.7K views
API All the Things!API All the Things!
API All the Things!
David Stockton620 views
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
David Stockton1.2K views
Hacking sites for fun and profitHacking sites for fun and profit
Hacking sites for fun and profit
David Stockton867 views
Beginning OOP in PHPBeginning OOP in PHP
Beginning OOP in PHP
David Stockton3.6K views
Common design patterns in phpCommon design patterns in php
Common design patterns in php
David Stockton1.7K views
Intermediate oop in phpIntermediate oop in php
Intermediate oop in php
David Stockton1.1K views
Grokking regexGrokking regex
Grokking regex
David Stockton1.7K views
Hacking sites for fun and profitHacking sites for fun and profit
Hacking sites for fun and profit
David Stockton4.5K views
Hacking sites for fun and profitHacking sites for fun and profit
Hacking sites for fun and profit
David Stockton8K views
Mercurial Distributed Version ControlMercurial Distributed Version Control
Mercurial Distributed Version Control
David Stockton1.6K views
Regular expressions and phpRegular expressions and php
Regular expressions and php
David Stockton1.7K views
FireBug And FirePHPFireBug And FirePHP
FireBug And FirePHP
David Stockton2.1K views

PHP 5 Magic Methods

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.