Prototypes and Ad-hoc objects
Auke van Slooten
auke@muze.nl
www.poefke.nl
Ad hoc objects
- Objects created 'in place'
- In PHP 7 as 'Anonymous Classes'
https://wiki.php.net/rfc/anonymous_classes
- You know this already from Javascript
var adHoc = {
property: 'world',
method: function() {
return 'hello '+this.property;
}
}
$adHoc = new class {
public $property = 'World';
public function method() {
return 'Hello '.$this->property;
}
}
Prototypes
- Inheritance for Objects, not Classes
- Not in PHP 7
- You know this already from Javascript
var adHoc2 = {
property: 'Moon'
}
adHoc2.prototype = adHoc;
adHoc2->method(); // => 'Hello Moon'
PHP 5.4?
This is cool, I want to use it now!
<?php
$adHoc = new adhoc([
'property' => 'World',
'method' => function() {
return 'Hello '.$this->property;
}
]);
?
<?php
class addHoc() {
public function __construct($props) {
foreach($props as $name => $value) {
$this->{$name} = $value;
}
}
}
?
Method 'method' not found.
Properties != Methods
:-(
!
Embrace the __magic

?
<?php
class addHoc() {
public function __call($name, $params) {
return call_user_func_array(
$this->{$name},
$params
);
}
}
!
"Hello " :-(
\Closure::bind(To)
<?php
class addHoc() {
public function __construct($props) {
foreach($props as $name => $value) {
if ( $value instanceof \Closure ) {
\Closure::bind( $value, $this );
}
$this->{$name} = $value;
}
}
}
:-)
"Hello World"
And prototypes...?
Prototypes and Ad-hoc objects
By Auke van Slooten
Prototypes and Ad-hoc objects
- 2,637