I thought it was high time I wrote an article with some code in it. Also one of my (now former ) colleagues - Cisco - asked me to write about this, so here I am.
Another new feature of PHP 7 (see the rest of my bumpf on PHP 7) is the ability to create anonymous classes. An anonymous class is to a named class what a closure (or anonymous function, or function expression) is to a named function. Well it kinda is. Only kinda cos I think they've ballsed-up their implementation.
Here's an example of an anonymous class in action:
// inline.php
$o = new class(17) {
private $x;
function __construct($x){
$this->x = $x;
}
function multiply($y){
return $this->x * $y;
}
};
$result = $o->multiply(19);
echo $result;
Here I use an anonymous class to create an object which is initialised with a property $x with a value of 17, and I then call a method to multiply that by 19. The output is predictable:
>php inline.php
323
>
323
>
This is all well and good, but an anonymous class should create a class, not an object. Obviously here it's creating the class inline, and then creating a new object out of it straight away. But what if I want to use this class again? I should be able to create just the class as a variable:
// classObject.php
$c = class {
private $x;
function __construct($x){
$this->x = $x;
}
function multiply($y){
return $this->x * $y;
}
};
$o = new $c(17);
$result = $o->multiply(19);
echo $result;
This should work. Here I'm declaring the class via the anonymous class expression, and then calling new on that class. However this just errors:
>php classObject.php
PHP Parse error: syntax error, unexpected 'class' (T_CLASS) in classObject.php on line 4
Parse error: syntax error, unexpected 'class' (T_CLASS) in classObject.php on line 4
>
PHP Parse error: syntax error, unexpected 'class' (T_CLASS) in classObject.php on line 4
Parse error: syntax error, unexpected 'class' (T_CLASS) in classObject.php on line 4
>
I have monkeyed as much as I can with the syntax, but I cannot get an anonymous class expression to actually return a class.
Let's think about this for a second, and here's an equivalent example with a function expression to contrast:
// functionExpressionType.php
function add($x, $y){
return $x + $y;
}
$addFunctionName = 'add';
printf('is_callable(add): %d%s', is_callable($addFunctionName), PHP_EOL);
$multiply = function($x, $y){
return $x * $y;
};
printf('is_callable($multiply): %d%s', is_callable($multiply), PHP_EOL);
Here I look at both a function declared via a function statement, and another declared via a function expression. In both cases, they return a callable (ie: a function):
>php functionExpressionType.php
is_callable(add): 1
is_callable($multiply): 1
>
is_callable(add): 1
is_callable($multiply): 1
>