require_once 和作用域
Coddy 面向 Dart 开发者的 PHP 课程的第 23 课,共 48 课。
Dart 库使用 import、可选前缀和 export 指令来组织声明。PHP 的 require_once 会在运行时执行文件,但不会自动创建命名空间。让依赖项相对于 __DIR__,并避免在仅包含声明的模块顶层输出内容。
require_once 在每个请求或 CLI 进程中最多执行一次文件。PHP 文件不会自动创建命名空间。将可复用的声明放在模块中,并避免在模块顶层输出内容。即使进程从其他位置启动,__DIR__ 也是稳定的目录锚点。明确地在使用依赖项的模块中 require 这些依赖项。
Dart 程序
String bracket(String text)=>"[$text]";
void main() {
print(bracket("ready"));
}
源代码输出:
[ready]PHP 程序
demo.php
<?php
declare(strict_types=1);
echo basename(__FILE__),"\n";
PHP 输出:
demo.php挑战
简单输入是两个介于 1..10000 之间的正整数。gcd 用于计算它们的最大公约数。Functions.php 通过相对于 __DIR__ 的 require_once 加载;主驱动程序负责输入和输出。
提供的主脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并打印结果。请实现模块声明,不要打印内容;不要替换启动程序,也不要从模块读取输入。输入符合所述类型和范围。
编辑 Functions.php。main.php 是锁定的入口文件。依赖项使用 require_once __DIR__ 和相对文件名。
亲手试试
<?php
declare(strict_types=1);
require_once __DIR__."/Functions.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure(gcd(21,14)===7 && gcd(1,100)===1,"module API");
echo (string)gcd(...$input),"\n";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Dart 开发者的 PHP中的所有课
自己练习: PHP 在线编译器