<?php
// php 中的匿名类 举例应用中的框架 需要 logger 日志打印
// 首先有应用类
/**
*
* @property Cache $cache
* @author Administrator
*
*/
class App
{
/**
*
* @var Log
*/
public $logger;
/**
*
* @return the $logger
*/
public function getLogger(): Log
{
return $this->logger;
}
/**
*
* @param Log $logger
*/
public function setLogger(Log $logger)
{
$this->logger = $logger;
}
/**
*
* @return the $cache
*/
public function getCache(): Cache
{
return $this->cache;
}
/**
*
* @param Cache $cache
*/
public function setCache(Cache $cache)
{
$this->cache = $cache;
}
}
// 然后就是 日志类的接口规范
interface Log
{
/**
*
* @param string $msg
* @return string
*/
public function getLogMsg(string $msg): string;
}
// 缓存规范接口
interface Cache
{
public function write(string $key, string $val): bool;
public function read(string $key): string;
}
$app = new App();
// php 实现匿名类
$app->setLogger(new class() implements Log {
/**
*
* {@inheritdoc}
*
* @see Log::getLogMsg()
*/
public function getLogMsg(string $msg): string
{
// TODO Auto-generated method stub
return $msg;
}
});
echo ($app->getLogger()->getLogMsg("jll")); //jllstring
$app->setCache(new class() implements Cache {
public $map = [];
/**
*
* {@inheritdoc}
*
* @see Cache::write()
*/
public function write(string $key, string $val): bool
{
// TODO Auto-generated method stub
$this->map[$key] = $val;
return true;
}
/**
*
* {@inheritdoc}
*
* @see Cache::read()
*/
public function read(string $key): string
{
// TODO Auto-generated method stub
return $this->map[$key];
}
});
$app->cache->write("weng", "miaomiao");
var_dump($app->cache->read("weng")); //miaomiao
最后修改:2019 年 09 月 05 日
© 允许规范转载