php8新特性详解及示例代码

更精简的构造函数和类型指定

name, $this->age) . PHP_EOL;
    }
}

$person = new Person(name: "church", age: 26);
$person->introduceSelf();

构造函数可以简写成这样了,用更少的代码初始化属性。
传参的时候,可以指定key,不用管顺序,随心所欲。

注解

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

php8新特性详解及示例代码_第1张图片

官方文档给出的<<>>语法是错的,让我很郁闷,还是去源码中找的测试用例。

php8新特性详解及示例代码_第2张图片

nullsafe语法糖

新增nullsafe,很方便的东西,代码又可以少写两行了。

ORM可以更愉快地玩耍了。

hasMany(Post::class);
    }
}

class Post
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

User::find(1)?->posts()->where("id", 1)->first()?->comments();

JIT

目前为止性能最强的PHP版本诞生了,又可以省两台服务器的钱了。

你可能感兴趣的:(php8)