php8新特性詳解及示例代碼

更精簡的構造函數和類型指定

<?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

image.png

官方文檔給出的<<>>語法是錯的,讓我很鬱悶,仍是去源碼中找的測試用例。函數

image.png

nullsafe語法糖

新增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();

JIT

目前爲止性能最強的PHP版本誕生了,又能夠省兩臺服務器的錢了。測試

相關文章
相關標籤/搜索