SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Downloaden Sie, um offline zu lesen
Magic Methods: Spilling the Secret
By Matthew Barlocker
The Barlocker
● Chief Architect at Lucid
Software Inc
● Started using PHP in 2005
● Graduated with BS in CS from
BYU in 2008
● Developed software for the
following industries:
– Network Security
– Social Gaming
– Financial
– Productivity
Magic Methods
● All object methods beginning with '__' are reserved.
● To gain the magic functionality, define the method on the
class.
<?php
class MyClass {
private $var1 = 5;
public function doSomething() {
echo "hello!n";
}
}
<?php
class MyClass {
private $var1 = 5;
public function doSomething() {
echo "hello!n";
}
public function __toString() {
return 'This is a MyClass';
}
}
Magic Methods
● Stringification
● Lifecycle
● Property Overloading
● Method Overloading
● Serialization
● Cloning
● Object Invocation
Stringification
● __toString
__toString
● public string __toString()
● Called when an object is cast as a string.
● Throwing an exception inside this method will cause a
fatal error.
● No default implementation.
__toString
<?php
class NoTostringExample {
public $a = 1;
}
$obj = new NoTostringExample();
echo "Stringified " . $obj . "n";
?>
$ php notostring.php
PHP Catchable fatal error: Object of class NoTostringExample could not be
converted to string in notostring.php on line 8
__toString
<?php
class TostringExample {
public $a = 2;
public function __toString() {
return 'TostringExample(' . $this->a . ')';
}
}
$obj = new TostringExample();
echo "Stringified " . $obj . "n";
?>
$ php tostring.php
Stringified TostringExample(2)
__toString
<?php
class BadTostringExample {
public $a = 3;
public function __toString() {
echo 'TostringExample(' . $this->a . ')' . "n";
}
}
$obj = new BadTostringExample();
echo "Stringified " . $obj . "n";
?>
$ php badtostring.php
TostringExample(3)
PHP Catchable fatal error: Method BadTostringExample::__toString() must return a
string value in badtostring.php on line 11
Lifecycle
● __construct
● __destruct
__construct
● public void __construct($params, …)
● Called when an object is first initialized.
● Must explicitly call parent::__construct() in children.
● Default implementation does nothing.
__destruct
● public void __destruct()
● Called when an object is garbage collected.
● Must explicitly call parent::__destruct() in children.
● Default implementation does nothing.
__destruct
● public void __destruct()
● Called when an object is garbage collected.
● Must explicitly call parent::__destruct() in children.
● Default implementation does nothing.
__construct / __destruct
$ php construct.php
Starting
Construct
Ending
Destruct
<?php
class Construct {
public function __construct() {
echo "Constructn";
}
public function __destruct() {
echo "Destructn";
}
}
echo "Startingn";
$obj = new Construct();
echo "Endingn";
?>
__construct / __destruct
<?php
class MyDB {
private $connection = null;
public function __construct($host, $user, $pass) {
$this->connection = dbconnect($host, $user, $pass);
}
public function __destruct() {
$this->connection->close();
}
}
Property Overloading
● __get
● __set
● __isset
● __unset
__get
● public mixed __get($name)
● Called when an inaccessible property is read.
● Not called in chains. ($x = $obj->noexist = 5;)
● Default implementation emits a warning and returns null
or emits a fatal error.
● Does not apply to static context.
__set
● public void __set($name, $value)
● Called to write a value to an inaccessible property.
● Default implementation adds a public variable to the
class.
● Does not apply to static context.
__isset
● public mixed __isset($name)
● Triggered by calling isset() or empty() on inaccessible
properties
● Default implementation checks for existence of property
and ignores visibility.
● Does not apply to static context.
__unset
● public mixed __unset($name)
● Triggered by calling unset() on inaccessible properties
● Default implementation removes accessible properties.
● Does not apply to static context.
Property Test
See code from
http://www.php.net/manual/en/language.oop5.overloading.php#object.get
Method Overloading
● __call
● __callStatic
__call
● public mixed __call($name, $params)
● Called when invoking inaccessible methods from an
object context.
__callStatic
● public static mixed __callStatic($name, $params)
● Called when invoking inaccessible methods from a static
context.
__call / __callStatic
<?php
class MethodTest
{
public function __call($name, $arguments)
{
echo "Calling object method '$name' " . implode(', ', $arguments). "n";
}
public static function __callStatic($name, $arguments)
{
echo "Calling static method '$name' " . implode(', ', $arguments). "n";
}
}
$obj = new MethodTest;
$obj->runTest(1, 2, 3, 'in object context');
MethodTest::runTest(4, 5, 6, 'in static context'); // As of PHP 5.3.0
?>
$ php methodtest.php
Calling object method 'runTest' 1, 2, 3, in object context
Calling static method 'runTest' 4, 5, 6, in static context
Serialization
● __sleep
● __wakeup
__sleep
● public array __sleep()
● Called when serialize() is called on the object.
● Returns an array of field names to include in the serialized
version of the object.
__wakeup
● public void __wakeup()
● Called when unserialize() is called on the serialized
object.
__sleep / __wakeup
See code from
http://www.php.net/manual/en/language.oop5.magic.php#object.sleep
Cloning
● __clone
● __set_state
__clone
● public void __clone()
● Called after the object is initialized.
● Default implementation does nothing.
__clone
See code from
http://www.php.net/manual/en/language.oop5.cloning.php#object.clone
__set_state
● public static void __set_state($properties)
● Called for classes exported by var_export().
__set_state
See code from
http://www.php.net/manual/en/language.oop5.magic.php#object.set-state
Object Invocation
● __invoke
__invoke
● public mixed __invoke($params, ...)
● Called when the object is treated like a function.
– $obj(1,2,3);
__invoke
<?php
class CallableClass
{
public function __invoke($x)
{
var_dump($x);
}
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>
$ php invoke.php
int(5)
bool(true)
Performance
● Each benchmark was run 10 times.
● Each run is shown as a different set of columns in the
graphs.
● Each run is exactly 1 million calls to the item being tested.
Performance
Performance
Performance
Performance
Performance
Performance
Thank you for your time.
Any Questions?
Lucid Software Inc
● Building the next generation of collaborative web
applications
● VC funded, high growth, profitable
● Graduates from Harvard, MIT, Stanford
● Team has worked at Google, Amazon, Microsoft
https://www.lucidchart.com/jobs

Weitere ähnliche Inhalte

Was ist angesagt?

Database Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDatabase Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::Class
Dave Cross
 
Orientação a Objetos no Delphi - Controle de Estoque (II)
Orientação a Objetos no Delphi - Controle de Estoque (II)Orientação a Objetos no Delphi - Controle de Estoque (II)
Orientação a Objetos no Delphi - Controle de Estoque (II)
Ryan Padilha
 
좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012
Daum DNA
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
Kumar
 

Was ist angesagt? (20)

Manipulação de formulários com PHP. Uso de Cookies e Session com PHP.
Manipulação de formulários com PHP. Uso de Cookies e Session com PHP.Manipulação de formulários com PHP. Uso de Cookies e Session com PHP.
Manipulação de formulários com PHP. Uso de Cookies e Session com PHP.
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
 
Database Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDatabase Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::Class
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
L11 array list
L11 array listL11 array list
L11 array list
 
Orientação a Objetos no Delphi - Controle de Estoque (II)
Orientação a Objetos no Delphi - Controle de Estoque (II)Orientação a Objetos no Delphi - Controle de Estoque (II)
Orientação a Objetos no Delphi - Controle de Estoque (II)
 
좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012좌충우돌 ORM 개발기 | Devon 2012
좌충우돌 ORM 개발기 | Devon 2012
 
Builder design pattern
Builder design patternBuilder design pattern
Builder design pattern
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
 
Collection v3
Collection v3Collection v3
Collection v3
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
 
Use Case Driven Development in Symfony
Use Case Driven Development in SymfonyUse Case Driven Development in Symfony
Use Case Driven Development in Symfony
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to hero
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 

Ähnlich wie Magic methods

EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
Enterprise PHP Center
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
Michael Girouard
 

Ähnlich wie Magic methods (20)

Lecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptxLecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptx
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Closer look at PHP Unserialization by Ashwin Shenoi
Closer look at PHP Unserialization by Ashwin ShenoiCloser look at PHP Unserialization by Ashwin Shenoi
Closer look at PHP Unserialization by Ashwin Shenoi
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnit
 
Effective PHP. Part 1
Effective PHP. Part 1Effective PHP. Part 1
Effective PHP. Part 1
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
 
Let's Talk Scope
Let's Talk ScopeLet's Talk Scope
Let's Talk Scope
 
PHPUnit your bug exterminator
PHPUnit your bug exterminatorPHPUnit your bug exterminator
PHPUnit your bug exterminator
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 

Mehr von Matthew Barlocker

Mehr von Matthew Barlocker (10)

Getting Started on Amazon EKS
Getting Started on Amazon EKSGetting Started on Amazon EKS
Getting Started on Amazon EKS
 
Optimizing Uptime in SOA
Optimizing Uptime in SOAOptimizing Uptime in SOA
Optimizing Uptime in SOA
 
Relate
RelateRelate
Relate
 
Highly Available Graphite
Highly Available GraphiteHighly Available Graphite
Highly Available Graphite
 
Nark: Steroids for Graphite
Nark: Steroids for GraphiteNark: Steroids for Graphite
Nark: Steroids for Graphite
 
ORM or SQL? A Better Way to Query in MySQL
ORM or SQL? A Better Way to Query in MySQLORM or SQL? A Better Way to Query in MySQL
ORM or SQL? A Better Way to Query in MySQL
 
Amazon EC2 to Amazon VPC: A case study
Amazon EC2 to Amazon VPC: A case studyAmazon EC2 to Amazon VPC: A case study
Amazon EC2 to Amazon VPC: A case study
 
Case Study: Lucidchart's Migration to VPC
Case Study: Lucidchart's Migration to VPCCase Study: Lucidchart's Migration to VPC
Case Study: Lucidchart's Migration to VPC
 
Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1
 
Git essentials
Git essentialsGit essentials
Git essentials
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Magic methods