1、trait
将类作为代码块引入EasySwoole\Core\AbstractInterface\Singleton.php文件
namespace EasySwoole\Core\AbstractInterface;
trait Singleton
{
private static $instance;
static function getInstance(...$args)
{
if(!isset(self::$instance)){
self::$instance = new static(...$args);
}
return self::$instance;
}
}
在需要用到的地方
引入use EasySwoole\Core\AbstractInterface\Singleton;
使用class Di
{
use Singleton;
private $container = array();
}
2、获取类名(包括命名空间)
use \App\Lib\RedisClient;
var_dump(RedisClient::class);// App\Lib\RedisClient
当需要传递类名用在其他地方实例化时,可以这样:
例如:Di::getInstance()->set('REDIS', RedisClient::class, \Yaconf::get('redis'));
3、三元运算符和isset()的简化
$id ?? '1' 等价于 $id ? $id : 1;
isset($_GET['id']) ? $_GET['id'] : 'err'; 等价于 $_GET['id'] ?? 'err';
4、限制函数的返回类型function test()?: array //限制返回值类型为null或数组
{
}
function test(): array //限制返回值类型为数组
{
}
5、匿名类new class implements Logger
6、函数参数类型的限制string, int, bool, float, array, classname,
function (string $name,int $id){ //name必须是字符串 id必须是int
}
7、批量引入命名空间use some\namespace\{ClassA, ClassB, ClassC as C};
8、三点号语法//从第二个参数开始,后面的参数将被注入到一个数组中
function test($param1, ...$args){
var_dump($args);
}
test(1, 2, 3, 4);
9、php反射类\ReflectionClass
\ReflectionMethod
本文为够意思原创文章,转载无需和我联系,但请注明来自够意思博客blog.go1s.cn:够意思博客 » php7新特性