Understanding the PHP Object Model

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    2 Favorites

    Understanding the PHP Object Model - Presentation Transcript

    1. Welcome! Understanding the PHP Object Model Sebastian Bergmann http://sebastian-bergmann.de/ December 5th 2008
    2. Outline ● Before we can “dive into” the object model of PHP, we need to understand the basic concepts of object-orientation
    3. Outline ● Before we can “dive into” the object model of PHP, we need to understand the basic concepts of object-orientation ● Then we can look at how PHP implements these concepts
    4. Outline ● Before we can “dive into” the object model of PHP, we need to understand the basic concepts of object-orientation ● Then we can look at how PHP implements these concepts ● Finally, we can look at what PHP supports in addition to the basic concepts of object-orientation
    5. Outline ● Before we can “dive into” the object model of PHP, we need to understand the basic concepts of object-orientation ● Then we can look at how PHP implements these concepts ● Finally, we can look at what PHP supports in addition to the basic concepts of object-orientation ● But first, let us have a quick look at a concept called type safety
    6. Type Safety Definition by Vijay Saraswat “A language is type-safe if the only operations that can be performed on data in the language are those sanctioned by the type of the data.”
    7. Type Safety ● Static Typing – Enforcement of Type Safety at Compile-Time ● Type associated with variable name upon declaration – Example Languages: C, C++, C#, Java
    8. Type Safety ● Static Typing – Enforcement of Type Safety at Compile-Time ● Type associated with variable name upon declaration – Example Languages: C, C++, C#, Java ● Dynamic Typing – Enforcement of Type Safety at Runtime ● Type associated with value upon creation – Example Languages: Lisp, PHP, Python, Smalltalk
    9. Type Safety ● Strong Typing – Restrictions on the intermixing of types that is permitted to occur – Explicit casting from one type to another – Example Languages: C++, C#, Lisp, Java, Python
    10. Type Safety ● Strong Typing – Restrictions on the intermixing of types that is permitted to occur – Explicit casting from one type to another – Example Languages: C++, C#, Lisp, Java, Python ● Weak Typing – “Not Strong Typing” ● Implicit casting from one type to another, for instance – Example Languages: C, JavaScript, PHP
    11. Type Safety in PHP Dynamic Typing <?php $variable = 'sebastian';
    12. Type Safety in PHP Dynamic Typing <?php $variable = 'sebastian'; $variable = 2204;
    13. Type Safety in PHP Dynamic Typing <?php $variable = 'sebastian'; $variable = 2204; $variable = array();
    14. Type Safety in PHP Dynamic Typing <?php $variable = 'sebastian'; $variable = 2204; $variable = array(); $variable = new StdClass; // ...
    15. Type Safety in PHP Weak Typing: Implicit Type Conversion <?php var_dump( 1 + 1 ); int(2)
    16. Type Safety in PHP Weak Typing: Implicit Type Conversion <?php var_dump( 1 + 1 ); var_dump('1' + '1'); int(2) int(2)
    17. Type Safety in PHP Weak Typing: Implicit Type Conversion <?php var_dump( 1 + 1 ); var_dump('1' + '1'); class One { public function __toString() { return '1'; } } var_dump(new One + new One); int(2) int(2) Notice: Object of class One could not be converted to int in /tmp/test.php on line 11 Notice: Object of class One could not be converted to int in /tmp/test.php on line 11 int(2)
    18. Type Safety in PHP Weak Typing: Implicit Type Conversion <?php var_dump( 1 + 1 ); var_dump('1' + '1'); class Two { public function __toString() { return '2'; } } var_dump(new Two + new Two); int(2) int(2) Notice: Object of class One could not be converted to int in /tmp/test.php on line 11 Notice: Object of class One could not be converted to int in /tmp/test.php on line 11 int(2)
    19. Type Safety in PHP Weak Typing: Explicit Type Conversion <?php var_dump( 1 + 1 ); var_dump('1' + '1'); class Two { public function __toString() { return '2'; } } var_dump((string)new Two + (string)new Two); int(2) int(2) int(4)
    20. What is Object-Orientation? Answer #1: Timothy A. Budd ● Everything is an object ● Objects communicate by sending messages ● Objects have private state ● Every object is an instance of one class ● A class can inherit from another class
    21. What is Object-Orientation? Answer #2: Benjamin C. Pierce ● Dynamic Dispatch ● Encapsulation ● Interface Inheritance ● Implementation Inheritance ● Open Recursion
    22. What is Object-Orientation? Answer #2: Benjamin C. Pierce ● Dynamic Dispatch Process of mapping a message to code at runtime ● Encapsulation ● Interface Inheritance ● Implementation Inheritance ● Open Recursion
    23. What is Object-Orientation? Answer #2: Benjamin C. Pierce ● Dynamic Dispatch ● Encapsulation Hiding of design decisions that are most likely to change ● Interface Inheritance ● Implementation Inheritance ● Open Recursion
    24. What is Object-Orientation? Answer #2: Benjamin C. Pierce ● Dynamic Dispatch ● Encapsulation ● Interface Inheritance Classes share a set of messages they understand ● Implementation Inheritance ● Open Recursion
    25. What is Object-Orientation? Answer #2: Benjamin C. Pierce ● Dynamic Dispatch ● Encapsulation ● Interface Inheritance ● Implementation Inheritance Classes share code ● Open Recursion
    26. What is Object-Orientation? Answer #2: Benjamin C. Pierce ● Dynamic Dispatch ● Encapsulation ● Interface Inheritance ● Implementation Inheritance ● Open Recursion A method can invoke another method on the same object via a special, late-bound variable
    27. OOP Syntax and Semantics in PHP Class Declaration <?php class Tomato { }
    28. OOP Syntax and Semantics in PHP Object Instantiation <?php require_once 'Tomato.php'; $tomato = new Tomato;
    29. OOP Syntax and Semantics in PHP Class Loading with __autoload() <?php $classes = array('Tomato' => 'Tomato.php'); function __autoload($className) { if (isset($classes[$className])) { require_once $classes[$className]; } } $tomato = new Tomato;
    30. OOP Syntax and Semantics in PHP Attributes: Object-Scope Variables <?php class Tomato { protected $utilized = FALSE; }
    31. OOP Syntax and Semantics in PHP Methods: Object-Scope Functions <?php class Tomato { protected $utilized = FALSE; public function utilize() { $this->utilized = TRUE; } }
    32. OOP Syntax and Semantics in PHP Methods: Object-Scope Functions <?php class Tomato { protected $utilized = FALSE; public function utilize() { $this->utilized = TRUE; } Late-bound variable that references the object that the method in which it is used has been called on }
    33. OOP Syntax and Semantics in PHP Visibility of Attributes and Methods <?php class Example { private $a = 'Can only be accessed by objects of the Example class'; protected $b = 'Can only be accessed by objects of the Example class or objects of classes that extend the Example class'; public $c = 'Can be accessed from every scope'; }
    34. OOP Syntax and Semantics in PHP Method Invokation <?php $tomato = new Tomato; $tomato->utilize();
    35. OOP Syntax and Semantics in PHP Visibility of Attributes and Methods <?php class Foo { public $bar = 'baz'; } $foo = new Foo; print $foo->bar; baz
    36. OOP Syntax and Semantics in PHP Visibility of Attributes and Methods <?php class Foo { private $bar = 'baz'; } $foo = new Foo; print $foo->bar; Fatal error: Cannot access private property Foo::$bar in /tmp/test.php on line 11
    37. OOP Syntax and Semantics in PHP Visibility of Attributes and Methods <?php class Foo { private $bar = 'baz'; public function doSomething(Foo $foo) { print $foo->bar; } } $foo = new Foo; $foo->doSomething(new Foo); baz
    38. Type Safety in PHP (continued) Type Hints <?php class Vector { public function add(Vector $vector) { // ... } } $x = new Vector; $x->add(new Vector);
    39. Type Safety in PHP (continued) Type Hints <?php class Vector { public function add($vector) { if (!($vector instanceof Vector)) { die('Argument must be a Vector object.'); } // ... } } $x = new Vector; $x->add(new Vector);
    40. Type Safety in PHP (continued) Type Hints <?php class Vector { public function add(Vector $vector) { // ... } } $x = new Vector; $x->add(new Vector);
    41. Type Safety in PHP (continued) Type Hints <?php class Vector { public function add(Vector $vector) { // ... } } $x = new Vector; $x->add(new StdClass); Catchable fatal error: Argument 1 passed to Vector::add() must be an instance of Vector, instance of stdClass given, called in /tmp/test.php on line 11 and defined in /tmp/test.php on line 4
    42. Type Safety in PHP (continued) Type Hints ● PHP 5.3 supports – array and class or interface names as argument type hints ● Support for scalar types might be added after PHP 5.3 – no type hints for ● attributes ● return values – Support for this might be added after PHP 5.3
    43. OOP Syntax and Semantics in PHP Raising Errors <?php class Tomato { protected $utilized = FALSE; public function utilize() { if (!$this->utilized) { $this->utilized = TRUE; } else { throw new Exception('Already utilized.'); } } }
    44. OOP Syntax and Semantics in PHP Handling Errors <?php $tomato = new Tomato; try { $tomato->utilize(); } catch (Exception $e) { print $e->getMessage(); }
    45. OOP Syntax and Semantics in PHP Special Methods: Constructor <?php class Tomato { protected $utilized; public function __construct() { $this->utilized = FALSE; } }
    46. OOP Syntax and Semantics in PHP Special Methods: Destructor <?php class Tomato { protected $utilized; public function __construct() { $this->utilized = FALSE; } public function __destruct() { if (!$this->utilized) { print \"Tomato spoiled.\\n\"; } } }
    47. OOP Syntax and Semantics in PHP Object Equality and Object Identity <?php $a = new StdClass; // Create new object $b = $a; // Reference object from another // another variable var_dump($a == $b); // bool(true) var_dump($a === $b); // bool(true)
    48. OOP Syntax and Semantics in PHP Object Equality and Object Identity <?php $a = new StdClass; // Create new object $b = $a; // Reference object from another // another variable var_dump($a == $b); // bool(true) var_dump($a === $b); // bool(true) $a->foo = 'bar'; // Set an attribute of the // object through one variable var_dump($a->foo); // string(3) \"bar\" var_dump($b->foo); // string(3) \"bar\"
    49. OOP Syntax and Semantics in PHP Object Equality and Object Identity <?php $a = new StdClass; // Create new object $b = $a; // Reference object from another // another variable var_dump($a == $b); // bool(true) var_dump($a === $b); // bool(true) $b = clone $a; // Create a copy of the object // referenced by $a var_dump($a == $b); // bool(true) var_dump($a === $b); // bool(false)
    50. OOP Syntax and Semantics in PHP Object Equality and Object Identity <?php $a = new StdClass; // Create new object $b = $a; // Reference object from another // another variable var_dump($a == $b); // bool(true) var_dump($a === $b); // bool(true) $b = clone $a; // Create a copy of the object // referenced by $a var_dump($a == $b); // bool(true) var_dump($a === $b); // bool(false) $a->foo = 'bar'; var_dump($a == $b); // bool(false)
    51. OOP Syntax and Semantics in PHP Special Methods: Clone Constructor <?php class Example { public function __construct() { print \"Example::__construct() called.\\n\"; } public function __clone() { print \"Example::__clone() called.\\n\"; } } $a = new Example; $b = clone $a; ?> Example::__construct() called. Example::__clone() called.
    52. Circular References <?php $root = new Node;
    53. Circular References <?php $root = new Node; $root->addChild(new Node);
    54. Circular References <?php $root = new Node; $root->addChild(new Node); unset($root); PHP 5.2 PHP 5.3 introduces a Garbage Collector that can deal with circular references
    55. Inheritance ● Single Inheritance – A class can inherit interface and implementation from a single parent class
    56. Inheritance ● Single Inheritance – A class can inherit interface and implementation from a single parent class ● Interfaces – A class can inherit interface and implementation from a single parent class – A class can implement multiple interfaces
    57. Inheritance ● Single Inheritance – A class can inherit interface and implementation from a single parent class ● Interfaces – A class can inherit interface and implementation from a single parent class – A class can implement multiple interfaces ● Multiple Inheritance – A class can inherit interface and implementation from multiple parent classes
    58. Inheritance <?php class Tomato {}
    59. Inheritance <?php class Vegetable {} class Tomato extends Vegetable {} ● Vegetable ● Tomato – is a type of Vegetable
    60. Inheritance <?php abstract class Vegetable {} class Tomato extends Vegetable {} ● Vegetable – is something abstract ● Tomato – is a type of Vegetable – is something concrete
    61. Inheritance <?php abstract class Item {} abstract class Food extends Item {} abstract class Vegetable extends Food {} class Tomato extends Vegetable {} ● Item ● Tomato – is something abstract – is a type of Vegetable ● Food – is something concrete – is a type of Item – is something abstract ● Vegetable – is a type of Food – is something abstract
    62. Inheritance <?php interface Edible {} interface Rollable {} interface Sellable {} interface Squeezable {} abstract class Item implements Sellable {} abstract class Food extends Item implements Edible {} abstract class Vegetable extends Food {} class Tomato extends Vegetable implements Rollable, Squeezable {} ● Item ● Vegetable – is something that can be sold – is a type of Food – is something abstract – is something abstract ● Food ● Tomato – is a type of Item – is a type of Vegetable – Is something that can be eaten – is something that can be squeezed – is something abstract – is something that can be rolled – is something concrete
    63. Inheritance <?php interface Edible {} interface Rollable {} interface Sellable {} interface Squeezable {} abstract class Item implements Sellable {} abstract class Food extends Item implements Edible {} abstract class Fruit extends Food {} abstract class Vegetable extends Food {} class Banana extends Fruit implements Squeezable {} class Tomato extends Vegetable implements Rollable, Squeezable {} ● Item ● Fruit – is something that can be sold – is a type of Food – is something abstract – is something abstract ● Food ● Banana – is a type of Item – is a type of Fruit – Is something that can be eaten – is something that can be squeezed – is something abstract – is something concrete
    64. Inheritance <?php interface Rollable { public function roll(); } abstract class Item {} abstract class Food extends Item {} abstract class Vegetable extends Food {} class Tomato extends Vegetable implements Rollable { public function roll() { // do something } }
    65. Inheritance <?php interface Rollable { public function roll(); } interface Sqeezable { public function sqeeze(); } abstract class Item {} abstract class Food extends Item {} abstract class Vegetable extends Food {} class Tomato extends Vegetable implements Rollable, Sqeezable { public function roll() { // do something; } public function squeeze() { $this->utilize(); return 'tomato juice'; } }
    66. Inheritance <?php class Juicer { public function squeeze(Squeezable $squeezable) { $juice = $squeezable->squeeze(); } }
    67. Inheritance <?php class Juicer { public function squeeze(Squeezable $squeezable) { $juice = $squeezable->squeeze(); } } class Roller { public function roll(Rollable $rollable) { $rollable->roll(); } }
    68. Object Context <?php class Food extends Item { protected $utilized; public function __construct() { printf(\"%s harvested\\n\", get_class($this)); $this->utilized = FALSE; } public function __destruct() { if (!$this->utilized) { printf(\"%s spoiled\\n\", get_class($this)); } } public function utilize() { $this->utilized = TRUE; } }
    69. Class Context Class Attributes <?php class Food extends Item { protected $utilized; protected static $statistics = array(); public function __construct() { printf(\"%s harvested\\n\", get_class($this)); $this->utilized = FALSE; self::$statistics[get_class($this)]['harvested']++; } public function __destruct() { if (!$this->utilized) { printf(\"%s spoiled\\n\", get_class($this)); self::$statistics[get_class($this)]['spoiled']++; } } public function utilize() { $this->utilized = TRUE; self::$statistics[get_class($this)]['utilized']++; } }
    70. Class Context Class Methods <?php class Food extends Item { // ... public static function utilizationRate($food) { return (self::$statistics[$food]['utilized'] / self::$statistics[$food]['harvested']) * 100 . '%'; } }
    71. Class Context Class Methods <?php class Food extends Item { // ... public static function utilizationRate($food) { return (self::$statistics[$food]['utilized'] / self::$statistics[$food]['harvested']) * 100 . '%'; } } $tomato = new Tomato; print Food::utilizationRate('Tomato'); Tomato harvested 0% Tomato spoiled
    72. Class Context Class Methods <?php class Food extends Item { // ... public static function utilizationRate($food) { return (self::$statistics[$food]['utilized'] / self::$statistics[$food]['harvested']) * 100 . '%'; } } $tomato = new Tomato; print Food::utilizationRate('Tomato'); $juicer = new Juicer; $juicer->squeeze(new Tomato); print Food::utilizationRate('Tomato'); Tomato harvested 0% Tomato harvested Tomato utilized 50% Tomato spoiled
    73. Class Context Early Static Binding <?php class Base { public static function a() { print \"Base::a() called\\n\"; self::b(); } public static function b() { print \"Base::b() called\\n\"; } } Base::a(); Base::a() called Base::b() called
    74. Class Context Early Static Binding <?php class Base { public static function a() { print \"Base::a() called\\n\"; self::b(); } public static function b() { print \"Base::b() called\\n\"; } } class Child extends Base { public static function b() { print \"Child::b() called\\n\"; } } Child::a(); Base::a() called Base::b() called
    75. Class Context Early Static Binding <?php class Base { public static function a() { ● self is replaced with the name print \"Base::a() called\\n\"; of the class it is used in at Base::b(); compile-time } public static function b() { print \"Base::b() called\\n\"; } } class Child extends Base { public static function b() { print \"Child::b() called\\n\"; } } Child::a(); Base::a() called Base::b() called
    76. Class Context Late Static Binding <?php class Base { public static function a() { ● self is replaced with the name print \"Base::a() called\\n\"; of the class it is used in at static::b(); compile-time } ● static is late-bound and evaluated at runtime public static function b() { print \"Base::b() called\\n\"; } } class Child extends Base { public static function b() { print \"Child::b() called\\n\"; } } Child::a(); Base::a() called Child::b() called
    77. Class Context Class Constants <?php class Example { const SOME_CONSTANT = 'some value'; public function aMethod($arg = self::SOME_CONSTANT) { } } print Example::SOME_CONSTANT; some value
    78. Interceptors ● __call($methodName, $arguments) ● __callStatic($methodName, $arguments) ● __get($attributeName) ● __set($attributeName, $value) ● __isset($attributeName)
    79. Storing Data in Objects Public Attributes <?php ● Attributes publicly accessible class Employee { public $id; – Attributes are also called public $name; fields or slots sometimes } ● No enforcement of value types
    80. Storing Data in Objects Protected Attributes and Accessor Methods <?php ● Attributes not directly accessible class Employee { protected $id; ● Enforcement of value types in protected $name; setter methods public function getId() { return $this->id; } public function setId($id) { if (is_int($id)) { $this->id = $id; } else { throw new InvalidArgumentException; } } // ... }
    81. Storing Data in Objects Protected Attributes and Accessor Methods <?php ● Attributes not directly accessible class Employee { protected $id; ● Enforcement of value types in protected $name; setter methods – But attributes might still be public function getId() { (unintentionally) accessed return $this->id; directly from “within” } public function setId($id) { if (is_int($id)) { $this->id = $id; } else { // ... } } // ... }
    82. Storing Data in Objects Protected Attributes and Accessor Methods <?php ● Attributes not directly accessible class Employee { protected $id; ● Enforcement of value types in protected $name; setter methods – But attributes might still be public function getId() { (unintentionally) accessed return $this->id; directly from “within” } ● No syntactic relationship public function setId($id) { between the attribute and the if (is_int($id)) { methods that manage it $this->id = $id; } else { // ... } } // ... }
    83. Storing Data in Objects Protected Attributes and Accessor Methods <?php ● Attributes not directly accessible class Employee { protected $id; ● Enforcement of value types in protected $name; setter methods – But attributes might still be public function getId() { (unintentionally) accessed return $this->id; directly from “within” } ● No syntactic relationship public function setId($id) { between the attribute and the if (is_int($id)) { methods that manage it $this->id = $id; ● These methods have to be called } else { explicitly by the accessing // ... context } } // ... }
    84. Storing Data in Objects Properties ● Construct in languages such as C# or Delphi – Just like an attribute, but access is automatically translated into method calls – Use Cases ● Type Checking ● Bounds Checking ● Read-Only Attributes ● Persistence ● ...
    85. Storing Data in Objects Properties ● Construct in languages such as C# or Delphi – Just like an attribute, but access is automatically translated into method calls – Use Cases ● Type Checking ● Bounds Checking ● Read-Only Attributes ● Persistence ● ... ● Can be implemented in PHP using the __get(), __set(), and __isset() interceptors – This is an idiom used in the eZ Components
    86. Interlude eZ Components ● Provide a solid platform for PHP application development ● Clean and simple API ● Excellent documentation ● Keep backward compatibility for longer periods of time ● Stable and few regressions ● Clean IP, Open Source friendly ● http://ezcomponents.org/
    87. Properties The eZ Components Way <?php class Employee { protected $properties = array( 'id' => NULL, 'name' => NULL ); public function __get($name) { switch ($name) { case 'id': case 'name': { return $this->properties[$name]; } } throw new ezcBasePropertyNotFoundException($name); } // ... }
    88. Properties The eZ Components Way <?php class Employee { public function __set($name, $value) { switch ($name) { case 'id': { if (is_int($value)) { $this->properties[$name] = $value; } } break; // ... } throw new ezcBasePropertyNotFoundException($name); } // ... }
    89. Properties The eZ Components Way <?php class Employee { // ... public function __isset($name) { switch ($name) { case 'id': case 'name': { return TRUE; } } return FALSE; } }
    90. Type-Safe Properties Annotations <?php ● By now we are used to annotate class Employee { /** attribute declarations with type * @var integer information */ protected $id; – This metadata is used, for instance, by PHPDocumentor /** to generate API documentation * @var string */ protected $name; }
    91. Type-Safe Properties Annotations <?php ● By now we are used to annotate class Employee { /** attribute declarations with type * @var integer information */ protected $id; – This metadata is used, for instance, by PHPDocumentor /** to generate API documentation * @var string */ – But it is also usefull when we protected $name; } want to automatically generate SQL queries or WSDL from an object
    92. Type-Safe Properties Annotations <?php ● By now we are used to annotate class Employee { /** attribute declarations with type * @var integer information */ protected $id; – This metadata is used, for instance, by PHPDocumentor /** to generate API documentation * @var string */ – But it is also usefull when we protected $name; } want to automatically generate SQL queries or WSDL from an object ● PHP allows read access to these docblocks at runtime through its Reflection API – So let us use this metadata for reusable __get() and __set() implementations
    93. Interlude Annotations and the Reflection API <?php class Employee { /** * @var integer */ protected $id; /** * @var string */ protected $name; } $class = new ReflectionClass('Employee'); $attributes = $class->getProperties(); foreach ($attributes as $attribute) { $docComment = $attribute->getDocComment(); if (preg_match('/@var[\\s]+([\\.\\w]+)/', $docComment, $matches)) { var_dump($matches[1]); } }
    94. Type-Safe Properties The TypeSafeObject Class <?php abstract class TypeSafeObject { protected $annotationsParsed = FALSE; protected $properties = array(); protected function parseAnnotations() { if (!$this->annotationsParsed) { $class = new ReflectionClass($this); $attributes = $class->getProperties(); foreach ($attributes as $attribute) { $docComment = $attribute->getDocComment(); if (preg_match('/@var[\\s]+([\\.\\w]+)/', $docComment, $matches)) { $this->properties[$attribute->getName()] = array( 'type' => $matches[1], 'value' => NULL ); } } $this->annotationsParsed = TRUE; } } // ...
    95. Type-Safe Properties The TypeSafeObject Class public function __get($name) { $this->parseAnnotations(); if (isset($this->properties[$name])) { return $this->properties[$name]['value']; } else { // ... } }
    96. Type-Safe Properties The TypeSafeObject Class public function __get($name) { $this->parseAnnotations(); if (isset($this->properties[$name])) { return $this->properties[$name]['value']; } else { // ... } } public function __set($name, $value) { $this->parseAnnotations(); if (isset($this->properties[$name]) ) { if (gettype($value) == $this->properties[$name]['type']) { $this->properties[$name]['value'] = $value; } else { // ... } } else { // ... } } // ...
    97. Type-Safe Properties The TypeSafeObject Class public function __isset($name) { $this->parseAnnotations(); return isset($this->properties[$name]); } }
    98. Type-Safe Properties Using the TypeSafeObject Class <?php class Employee extends TypeSafeObject { /** * @var integer */ protected $id; /** * @var string */ protected $name; }
    99. Type-Safe Properties Using the TypeSafeObject Class <?php class Employee extends TypeSafeObject { /** * @var integer */ protected $id; /** * @var string */ protected $name; } $e = new Employee; var_dump($e->id); NULL
    100. Type-Safe Properties Using the TypeSafeObject Class <?php class Employee extends TypeSafeObject { /** * @var integer */ protected $id; /** * @var string */ protected $name; } $e = new Employee; $e->id = '123'; var_dump($e->id); NULL
    101. Type-Safe Properties Using the TypeSafeObject Class <?php class Employee extends TypeSafeObject { /** * @var integer */ protected $id; /** * @var string */ protected $name; } $e = new Employee; $e->id = 123; var_dump($e->id); int(123)
    102. Type-Safe Properties Problems with the TypeSafeObject Class <?php ● Conceptual problem abstract class TypeSafeObject { // ... – Employee is a TypeSafeObject } class Employee extends TypeSafeObject { /** * @var integer */ protected $id; /** * @var string */ protected $name; }
    103. Type-Safe Properties Problems with the TypeSafeObject Class <?php ● Conceptual problem abstract class TypeSafeObject { // ... – Employee is a TypeSafeObject } – This usually does not fit into our model class Person extends TypeSafeObject { // ... } class Employee extends Person { /** * @var integer */ protected $id; /** * @var string */ protected $name; }
    104. Type-Safe Properties Problems with the TypeSafeObject Class <?php ● Conceptual problem abstract class TypeSafeObject { // ... – Employee is a TypeSafeObject } – This usually does not fit into our model class Person extends TypeSafeObject { // ... ● PHP 5.3 supports } – Single Implementation Inheritance class Employee extends Person { /** – Multiple Interface Inheritance * @var integer */ protected $id; /** * @var string */ protected $name; }
    105. Type-Safe Properties Traits to the rescue! <?php ● Conceptual problem trait TypeSafeObject { // ... – Employee is a TypeSafeObject } – This usually does not fit into our model class Person { use TypeSafeObject; ● PHP 5.3 supports // ... – Single Implementation Inheritance } – Multiple Interface Inheritance class Employee extends Person { /** ● Future versions of PHP will support * @var integer Traits */ protected $id; – Safe variant of multiple implementation inheritance /** * @var string ● A class can implement multiple */ interfaces protected $name; ● A class can extend a single class } ● A class can use multiple traits – Reuse sets of methods freely in several independent classes living in different class hierarchies
    106. The End ● Thank you for your interest! ● These slides will be available shortly on http://sebastian-bergmann.de/talks/.
    107. License   This presentation material is published under the Attribution-Share Alike 3.0 Unported license.   You are free: ✔ to Share – to copy, distribute and transmit the work. ✔ to Remix – to adapt the work.   Under the following conditions: ● Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). ● Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license.   For any reuse or distribution, you must make clear to others the license terms of this work.   Any of the above conditions can be waived if you get permission from the copyright holder.   Nothing in this license impairs or restricts the author's moral rights.

    + Sebastian BergmannSebastian Bergmann, 2 years ago

    custom

    2139 views, 2 favs, 0 embeds more stats

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 2139
      • 2139 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 2
    • Downloads 49
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories