<?php class Person { public function __construct( public int $age = 0, public string $name = '' ) {} public function introduceSelf(): void { echo sprintf("Hi, This is %s, I'm %d years old.", $this->name, $this->age) . PHP_EOL; } } $person = new Person(name: "church", age: 26); $person->introduceSelf();
构造函数能够简写成这样了,用更少的代码初始化属性。
传参的时候,能够指定key,不用管顺序,为所欲为。php
<?php #[Attribute] class Route { public function __construct( public string $path = '/', public array $methods = [] ) {} } #[Attribute] class RouteGroup { public function __construct( public string $basePath = "/" ) {} } #[RouteGroup("/index")] class IndexController { #[Route("/index", methods: ["get"])] public function index(): void { echo "hello!world" . PHP_EOL; } #[Route("/test", methods: ["get"])] public function test(): void { echo "test" . PHP_EOL; } } class Kernel { protected array $routeGroup = []; public function handle($argv): void { $this->parseRoute(); [,$controller, $method] = explode('/', $argv[1]); [$controller, $method] = $this->routeGroup['/' . $controller]['get']['/'. $method]; call_user_func_array([new $controller, $method], []); } public function parseRoute(): void { $controller = new ReflectionClass(IndexController::class); $controllerAttributes = $controller->getAttributes(RouteGroup::class); foreach ($controllerAttributes as $controllerAttribute) { [$groupName] = $controllerAttribute->getArguments(); $methods = $controller->getMethods(ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { $methodAttributes = $method->getAttributes(Route::class); foreach ($methodAttributes as $methodAttribute) { [0 => $path, 'methods' => $routeMethods] = $methodAttribute->getArguments(); foreach ($routeMethods as $routeMethod) { $this->routeGroup[$groupName][$routeMethod][$path] = [IndexController::class, $method->getName()]; } } } } } } $kernel = new Kernel; $kernel->handle($argv); //cli模式下运行 php test.php /index/index
执行服务器
php test.php /index/test
官方文档给出的<<>>
语法是错的,让我很郁闷,仍是去源码中找的测试用例。函数
新增nullsafe
,很方便的东西,代码又能够少写两行了。post
ORM
能够更愉快地玩耍了。性能
<?php class User { public function posts() { return $this->hasMany(Post::class); } } class Post { public function comments() { return $this->hasMany(Comment::class); } } User::find(1)?->posts()->where("id", 1)->first()?->comments();
目前为止性能最强的PHP版本诞生了,又能够省两台服务器的钱了。测试