SlideShare a Scribd company logo
1 of 46
Download to read offline
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

More Related Content

What's hot

What's hot (20)

Grails GORM - You Know SQL. You Know Queries. Here's GORM.
Grails GORM - You Know SQL. You Know Queries. Here's GORM.Grails GORM - You Know SQL. You Know Queries. Here's GORM.
Grails GORM - You Know SQL. You Know Queries. Here's GORM.
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Php internal architecture
Php internal architecturePhp internal architecture
Php internal architecture
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
6 things you need to know about GORM 6
6 things you need to know about GORM 66 things you need to know about GORM 6
6 things you need to know about GORM 6
 
PHP MVC
PHP MVCPHP MVC
PHP MVC
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Rust
RustRust
Rust
 
React & GraphQL
React & GraphQLReact & GraphQL
React & GraphQL
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Tutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPTutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHP
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
PHP POSTGRESQL integration
PHP POSTGRESQL  integrationPHP POSTGRESQL  integration
PHP POSTGRESQL integration
 
HeadLess Drupal
HeadLess DrupalHeadLess Drupal
HeadLess Drupal
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
 

Similar to 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
 

Similar to 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?
 

More from Matthew Barlocker

More from 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
 

Recently uploaded

Microsoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdfMicrosoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdf
Overkill Security
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)
Wonjun Hwang
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
FIDO Alliance
 

Recently uploaded (20)

Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Microsoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdfMicrosoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdf
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxCyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
 
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
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdfFrisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 

Magic methods