46
Magic Methods: Spilling the Secret By Matthew Barlocker

Magic methods

Embed Size (px)

DESCRIPTION

Originally presented at Northeast PHP 2013.

Citation preview

Page 1: Magic methods

Magic Methods: Spilling the Secret

By Matthew Barlocker

Page 2: Magic methods

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

Page 3: Magic methods

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'; }}

Page 4: Magic methods

Magic Methods

● Stringification

● Lifecycle

● Property Overloading

● Method Overloading

● Serialization

● Cloning

● Object Invocation

Page 5: Magic methods

Stringification● __toString

Page 6: Magic methods

__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.

Page 7: Magic methods

__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

Page 8: Magic methods

__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)

Page 9: Magic methods

__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

Page 10: Magic methods

Lifecycle

● __construct

● __destruct

Page 11: Magic methods

__construct

● public void __construct($params, …)

● Called when an object is first initialized.

● Must explicitly call parent::__construct() in children.

● Default implementation does nothing.

Page 12: Magic methods

__destruct

● public void __destruct()

● Called when an object is garbage collected.

● Must explicitly call parent::__destruct() in children.

● Default implementation does nothing.

Page 13: Magic methods

__destruct

● public void __destruct()

● Called when an object is garbage collected.

● Must explicitly call parent::__destruct() in children.

● Default implementation does nothing.

Page 14: Magic methods

__construct / __destruct

$ php construct.php StartingConstructEndingDestruct

<?php

class Construct {public function __construct() {

echo "Construct\n";}

public function __destruct() {echo "Destruct\n";

}}

echo "Starting\n";$obj = new Construct();echo "Ending\n";

?>

Page 15: Magic methods

__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(); }}

Page 16: Magic methods

Property Overloading

● __get

● __set

● __isset

● __unset

Page 17: Magic methods

__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.

Page 18: Magic methods

__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.

Page 19: Magic methods

__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.

Page 20: Magic methods

__unset

● public mixed __unset($name)

● Triggered by calling unset() on inaccessible properties

● Default implementation removes accessible properties.

● Does not apply to static context.

Page 21: Magic methods

Property Test

See code fromhttp://www.php.net/manual/en/language.oop5.overloading.php#object.get

Page 22: Magic methods

Method Overloading

● __call

● __callStatic

Page 23: Magic methods

__call

● public mixed __call($name, $params)

● Called when invoking inaccessible methods from an object context.

Page 24: Magic methods

__callStatic

● public static mixed __callStatic($name, $params)

● Called when invoking inaccessible methods from a static context.

Page 25: Magic methods

__call / __callStatic<?phpclass 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.phpCalling object method 'runTest' 1, 2, 3, in object contextCalling static method 'runTest' 4, 5, 6, in static context

Page 26: Magic methods

Serialization

● __sleep

● __wakeup

Page 27: Magic methods

__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.

Page 28: Magic methods

__wakeup

● public void __wakeup()

● Called when unserialize() is called on the serialized object.

Page 29: Magic methods

__sleep / __wakeup

See code fromhttp://www.php.net/manual/en/language.oop5.magic.php#object.sleep

Page 30: Magic methods

Cloning

● __clone

● __set_state

Page 31: Magic methods

__clone

● public void __clone()

● Called after the object is initialized.

● Default implementation does nothing.

Page 32: Magic methods

__clone

See code fromhttp://www.php.net/manual/en/language.oop5.cloning.php#object.clone

Page 33: Magic methods

__set_state

● public static void __set_state($properties)

● Called for classes exported by var_export().

Page 34: Magic methods

__set_state

See code fromhttp://www.php.net/manual/en/language.oop5.magic.php#object.set-state

Page 35: Magic methods

Object Invocation

● __invoke

Page 36: Magic methods

__invoke

● public mixed __invoke($params, ...)

● Called when the object is treated like a function.

– $obj(1,2,3);

Page 37: Magic methods

__invoke

<?phpclass CallableClass{ public function __invoke($x) { var_dump($x); }}$obj = new CallableClass;$obj(5);var_dump(is_callable($obj));?>

$ php invoke.phpint(5)bool(true)

Page 38: Magic methods

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.

Page 39: Magic methods

Performance

Page 40: Magic methods

Performance

Page 41: Magic methods

Performance

Page 42: Magic methods

Performance

Page 43: Magic methods

Performance

Page 44: Magic methods

Performance

Page 45: Magic methods

Thank you for your time.Any Questions?

Page 46: Magic methods

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