
# 简介

Phasis是用PHP编写的JavaScript引擎。它会在调用它的PHP进程中词法分析、解析并执行 ECMAScript：无需`exec('node …')`、FFI 或自定义二进制扩展。它以Composer包`phasis/phasis`的形式发布。

它需要PHP 8.2 或更高版本，并依赖三个标准扩展：`ext-mbstring`、`ext-bcmath`（用于 BigInt 运算和整数精度数值处理）以及`ext-curl`（默认`fetch()`传输）。[入门](https://phasis.inline0.dev/zh/docs/getting-started/#install)介绍了如何在未包含`bcmath`的构建中添加它，例如官方的`php` Docker镜像。

有两个可选扩展：`ext-intl`可启用`Intl` API 和非ISO Temporal日历；`ext-openssl`则可启用`crypto.subtle` AES 加密。

PHP应用需要运行JavaScript，例如模板渲染、组件的服务器端渲染、与浏览器共享的验证规则，或沙箱中的用户脚本，通常会调用Node.js，否则就放弃此功能。另一个运行时会带来序列化边界、子进程管理，以及在共享主机上更复杂的部署。Phasis会让JavaScript留在PHP进程中，并让PHP和JavaScript直接交换值并互相调用。

## 首个示例

```bash
composer require phasis/phasis
```

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use Phasis\Engine;

$engine = new Engine();

$engine->setGlobal('order', [
    'items' => [
        ['name' => 'Notebook', 'price' => 12.5, 'qty' => 2],
        ['name' => 'Pen', 'price' => 4, 'qty' => 3],
    ],
]);
$engine->setGlobal('money', fn (float $amount): string => number_format($amount, 2) . ' EUR');

$total = $engine->eval('
    const total = order.items.reduce((sum, item) => sum + item.price * item.qty, 0);
    console.log(`${order.items.length} items, ${money(total)}`);
    total;
');

echo $total;
// 37

echo $engine->getConsoleOutput();
// 2 items, 37.00 EUR

$engine->eval('function label(amount) { return `Total: ${money(amount)}`; }');
echo $engine->call('label', $total);
// Total: 37.00 EUR
```

这里发生了什么：

- `setGlobal()`会将PHP数组复制到JavaScript中，作为一个带有`items`数组的对象。[值转换规则](https://phasis.inline0.dev/zh/docs/interop/values/)说明了两种方向上的每种类型转换。
- `money`是PHP闭包。JavaScript像调用任何函数一样调用它；参数和返回值会在边界处进行转换。参见[宿主函数](https://phasis.inline0.dev/zh/docs/interop/host-functions/)。
- `eval()`会将源代码作为经典脚本运行，清空事件循环，并返回最后一个表达式转换为PHP后的值。
- `console.log()`会写入引擎的缓冲区，而不是 stdout。使用`getConsoleOutput()`读取。
- 引擎会保留其全局状态，因此后续的`eval()`或`call()`会看到`total`、`money`和`label`。

渲染组件的方式相同，无需构建步骤：

```php
$html = $engine->renderSource(
    "export default ({ name }) => <p>Hello {name}</p>;",
    ['name' => 'Ada'],
);
// <p>Hello <!-- -->Ada</p>
```

## 它运行什么

- **经典脚本。** `eval()` 和 `execFile()` 在 `.js` 文件中运行脚本时，会在全局作用域中执行。参见 [API](https://phasis.inline0.dev/zh/docs/api/#eval)。
- **ES 模块。** `evalAsModule()` 和 `execFile()` 在 `.mjs` 文件中通过模块加载器运行模块。无需构建步骤即可解析导入：相对路径和省略扩展名的路径、`index` 文件、导入映射、`jsconfig` 别名、通过 `package.json` `exports` 的 `node_modules`、CommonJS 包，以及样式和资源导入。参见 [模块](https://phasis.inline0.dev/zh/docs/modules/)。
- **TypeScript。** 执行、导入或渲染 `.ts`、`.tsx`、`.mts` 和 `.cts` 文件时，原生 PHP 解析器会擦除其中的类型。参见 [TypeScript](https://phasis.inline0.dev/zh/docs/typescript/)。
- **JSX 和 React。** `render()` 和 `renderSource()` 会将组件模块渲染为 HTML 字符串。React 配置生成的 HTML 与 `react-dom@19.3.1` 字节完全相同，React 可在浏览器中对其进行 hydration；而 `renderForHydration()` 会将该字符串与 HTML 所需的 props 配对。HTML 配置则与 `preact-render-to-string` 6.8.1 匹配，适用于电子邮件、信息流和静态页面。参见 [JSX](https://phasis.inline0.dev/zh/docs/jsx/) 和 [React](https://phasis.inline0.dev/zh/docs/react/)。
- **兼容 Node.js 的包。** `enableNode()` 或 `phasis --node` 会添加 CommonJS、`Buffer`、流、文件系统访问、HTTP 服务器和客户端、TLS、加密功能和计时器，所有内容均在 PHP 中执行。对 Express 和 Hono 的支持仍处于实验阶段。参见 [Node 兼容性](https://phasis.inline0.dev/zh/docs/modules/#node-compatibility)。
- **Web 平台 API。** `URL`、`URLSearchParams`、`TextEncoder`/`TextDecoder`、`atob`/`btoa`、`structuredClone`、`performance` 和 `DOMException`。参见 [Web API](https://phasis.inline0.dev/zh/docs/compatibility/web-apis/)。
- **Fetch。** `fetch()` 配合 `Request`、`Response`、`Headers`、`AbortController`/`AbortSignal`、`Blob`、`File`、`FormData`、`EventTarget` 和 WHATWG Streams 使用。
- **加密、套接字和计时器。** `crypto` 配合 `SubtleCrypto`、`WebSocket`、`XMLHttpRequest`、计时器和 `queueMicrotask` 使用。

ECMAScript 标准库功能齐全，包括 `Proxy`、`Reflect`、`Symbol`、`BigInt`、类型化数组、`Temporal` 和 `Intl`；现代语法特性也一应俱全，例如带私有字段和装饰器的类、异步生成器，以及模块顶层的 `await`。[规范功能列表](https://phasis.inline0.dev/zh/docs/compatibility/spec-surface/)列出了这些内容。

引擎的两个部分也可以单独使用：[解析器](https://phasis.inline0.dev/zh/docs/parser/)可将源代码转换为带类型的 PHP AST 或符合 ESTree 结构的数组，而不会执行代码；[格式化器](https://phasis.inline0.dev/zh/docs/formatter/)则以兼容 Prettier 的布局格式化 JavaScript、JSON 和 CSS。

## 由宿主控制

PHP 应用决定 JavaScript 可以访问哪些内容，以及运行时长：

- 网络访问通过可替换的[fetch transport](https://phasis.inline0.dev/zh/docs/interop/fetch-transport/)进行，并可选用策略钩子来重写或拒绝每个请求。该钩子涵盖`fetch()`、`XMLHttpRequest`和`WebSocket`握手。它不涵盖 Node 模式的`http`、`https`、`net`、`tls`、`http2`和`child_process`模块；因此，当该钩子是安全边界时，请关闭[Node 兼容性](https://phasis.inline0.dev/zh/docs/modules/#node-compatibility)。除非挂载[Cookie jar](https://phasis.inline0.dev/zh/docs/interop/cookie-jar/)，否则 Cookie 处于关闭状态。
- 事件循环在虚拟时间上运行：`setTimeout(cb, 5000)`会在`eval()`返回之前触发，期间不会PHP休眠。请参阅[事件循环](https://phasis.inline0.dev/zh/docs/api/#event-loop)。
- `setLimit('maxLoopIterations', …)`限制每个循环的迭代次数，[`setExecutionBudget()`](https://phasis.inline0.dev/zh/docs/api/#setexecutionbudget)会在达到墙上时钟时间预算后停止求值，并且固定的调用栈上限会阻止失控的递归。字符串长度和控制台输出不受限制。请参阅[setLimit](https://phasis.inline0.dev/zh/docs/api/#setlimit)。
- 传递给JavaScript的PHP对象会按引用公开其公共属性和方法；请参阅[共享对象](https://phasis.inline0.dev/zh/docs/interop/shared-objects/)。

## 验证方式

Node.js（V8）是参照标准：当V8产生结果时，Phasis必须产生相同结果。每个拉取请求以及推送到头部提交带有`[ci]`的`main`时，CI 都会运行PHPStan、PHPCS、单元测试套件和对照场景，将Phasis输出与 Node 进行比较；引擎源代码发生变化时，还会运行 Web Platform Tests 和热门软件包测试套件。固定版本的官方test262测试套件符合性检查由 CI 手动运行，结果会提交到`COMPAT.md`；[test262](https://phasis.inline0.dev/zh/docs/compatibility/test262/)说明快照，而[兼容性](https://phasis.inline0.dev/zh/docs/compatibility/)汇总测试结果。

## 它不是什么

Phasis 并非 JIT 编译器，而是一个树遍历解释器，带有机会式字节码虚拟机，可将受支持的热点函数编译为 PHP 闭包。在受分派开销限制的工作负载中，运行时间预计约为 100 倍于 V8。这种取舍带来纯 PHP 运行时，无需额外进程，执行过程也由宿主控制；对于嵌入式场景，当正确性和隔离比原始吞吐量更重要时，这种方式很合适。参见 [基准测试](https://phasis.inline0.dev/zh/docs/advanced/benchmarks/) 和 [限制](https://phasis.inline0.dev/zh/docs/compatibility/limitations/)。

## 文档结构

### 从这里开始

[入门](https://phasis.inline0.dev/zh/docs/getting-started/)会安装 Phasis，并从 CLI 和 PHP 运行第一个脚本。[CLI](https://phasis.inline0.dev/zh/docs/cli/)介绍 `bin/phasis`、`bin/test262` 和 `bin/wpt`。

### 嵌入参考

[API](https://phasis.inline0.dev/zh/docs/api/) 是 `Phasis\Engine`参考文档，涵盖求值、渲染、全局变量、控制台输出、限制、事件循环、fetch 钩子、异常和生命周期。

### 互操作

[互操作](https://phasis.inline0.dev/zh/docs/interop/)说明了 PHP 与 JavaScript 之间的边界。[值转换](https://phasis.inline0.dev/zh/docs/interop/values/)、[宿主函数](https://phasis.inline0.dev/zh/docs/interop/host-functions/) 和 [共享对象](https://phasis.inline0.dev/zh/docs/interop/shared-objects/)介绍了数据和调用如何跨越这一边界。

要从 JavaScript 访问网络，请阅读[fetch 传输](https://phasis.inline0.dev/zh/docs/interop/fetch-transport/)、[Cookie 存储](https://phasis.inline0.dev/zh/docs/interop/cookie-jar/)和[中止操作模式](https://phasis.inline0.dev/zh/docs/interop/abort-patterns/)页面。

### 语言和渲染

[TypeScript](https://phasis.inline0.dev/zh/docs/typescript/)、[JSX](https://phasis.inline0.dev/zh/docs/jsx/)、[React](https://phasis.inline0.dev/zh/docs/react/) 和 [模块](https://phasis.inline0.dev/zh/docs/modules/)介绍了文件类型、渲染配置、水合和导入解析。

### 兼容性

[兼容性](https://phasis.inline0.dev/zh/docs/compatibility/)汇总了符合性结果：[test262](https://phasis.inline0.dev/zh/docs/compatibility/test262/)、[Web API](https://phasis.inline0.dev/zh/docs/compatibility/web-apis/) 和 [流](https://phasis.inline0.dev/zh/docs/compatibility/streams/)。

[热门包](https://phasis.inline0.dev/zh/docs/compatibility/popular-packages/)列出了针对 Node.js 检查过的 npm 库，[规范范围](https://phasis.inline0.dev/zh/docs/compatibility/spec-surface/)介绍了已实现的内置功能，而[限制](https://phasis.inline0.dev/zh/docs/compatibility/limitations/)说明了 Phasis 与 V8 的差异。

### 独立工具

[解析器](https://phasis.inline0.dev/zh/docs/parser/) 和 [格式化器](https://phasis.inline0.dev/zh/docs/formatter/)介绍了无需执行代码即可使用的 API。

### 内部机制

[高级](https://phasis.inline0.dev/zh/docs/advanced/)介绍了[架构](https://phasis.inline0.dev/zh/docs/advanced/architecture/)、[字节码 VM](https://phasis.inline0.dev/zh/docs/advanced/bytecode-vm/)、[测试模型](https://phasis.inline0.dev/zh/docs/advanced/testing/) 和 [基准测试](https://phasis.inline0.dev/zh/docs/advanced/benchmarks/)。
