- Building RESTful Web Services with PHP 7
- Haafiz Waheed ud din Ahmad
- 124字
- 2021-07-03 00:02:23
Anonymous classes
Just like anonymous functions, now there are anonymous classes in PHP. Note that if an object is required, then most probably we need some specific type of object and not just a random one, for example:
<?php
class App
{
public function __construct()
{
//some code here
}
}
function useApp(App $app)
{
//use app somewhere
}
$app = new App();
useApp($app);
Note that a specific type of object was required in the useApp() function, and this type App couldn't be defined if it wasn't a class. So, where and why would we use an anonymous class with some specific functionality in it? We may need it in case we need to pass a class implementing some specific interface or extending some parent class, but only want to have this class used in one place. In that case, we can use an anonymous class.
Here is the same example given in the PHP7 documentation so that it will be easy for you to follow up:
<?php
interface Logger {
public function log(string $msg);
}
class Application {
private $logger;
public function getLogger(): Logger {
return $this->logger;
}
public function setLogger(Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setLogger(new class implements Logger {
public function log(string $msg) {
echo $msg;
}
});
var_dump($app->getLogger()); //object(class@anonymous)#2 (0) {}
As you can see, although an anonymous class object is passed here in $app->setLogger(), it could be a named class object as well. So, an anonymous class object can be replaced by a named class object. However, it is better to use an anonymous class object when we don't want to use the object of the same class again.