本篇文章給大家?guī)砹岁P(guān)于php8.3的最新相關(guān)信息,其中主要介紹了PHP8.3將會添加名為json_validate的函數(shù),那么這個函數(shù)有什么用呢?怎么使用它呢?下面一起來看一下,希望對大家有幫助。
PHP 8.3 前瞻:`json_validate` 函數(shù)
PHP 8.3 將會添加名為 json_validate 的函數(shù),用于驗(yàn)證傳入的字符串是否是合法的 JSON 字符串。
在目前,驗(yàn)證 JSON 字符串的一種通用做法是嘗試將其解碼,并通過捕獲異常來確定。但某些情況下我們可能并不需要獲得具體的內(nèi)容,只需要驗(yàn)證其合法。新的 json_validate 函數(shù)相比 json_decode 耗用的內(nèi)存和資源更少,因?yàn)樗环治鲎址粫L試解碼。
函數(shù)簽名
/** * 驗(yàn)證傳入的字符串是否為合法 JSON 字符串 * * @param string $json 準(zhǔn)備驗(yàn)證的字符串 * @param int $depth 最大嵌套深度,必須大于 0 * @param int $flags 標(biāo)志掩碼,用于指定行為 * @return bool $json 是合法 JSON 字符串時返回 true,否則返回 false */ function json_validate(string $json, int $depth = 512, int $flags = 0): bool {}
標(biāo)志 Flags
json_validate 的第三個參數(shù)是 flags,用于指定函數(shù)的行為。在目前,唯一可用的標(biāo)志是 JSON_INVALID_UTF8_IGNORE。
該標(biāo)志在 PHP 7.2 中添加,作為 json_decode 的標(biāo)志常量,用于忽略對應(yīng)字符串中的 UTF-8 字符。
json_validate('[1, 2, 3]', flags: JSON_INVALID_UTF8_IGNORE); // true json_validate("["xc1xc1","a"]"); // false json_validate("["xc1xc1","a"]", flags: JSON_INVALID_UTF8_IGNORE); // true
錯誤處理
json_validate 本身并不會返回錯誤碼,如果你想要獲取具體的錯誤信息,可用使用 json_last_error 和 json_last_error_msg 獲取。
json_validate(""); // false json_last_error(); // 4 json_last_error_msg(); // "Syntax error"
json_validate("null"); // true json_last_error(); // 0 json_last_error_msg(); // "No error"
示例
驗(yàn)證字符串并拋出異常
if (json_validate($_GET['json']) === false) { throw new JsonException(json_last_error_msg(), json_last_error()); }
替代以前的驗(yàn)證方式
- $value = json_decode($_GET['json'], flags: JSON_THROW_ON_ERROR); + if (!json_validate($_GET['json'])) { + throw new JsonException(json_last_error_msg(), json_last_error()); + } + $value = json_decode($_GET['json']);
Polyfill 搶先適配
如果你想提前為 PHP 8.3 做適配,以在 8.3 發(fā)布的第一時間無縫切換到 json_validate,你可以手動定義一個函數(shù),以在之前的版本中模仿 json_validate 的作用。
if (!function_exists('json_validate')) { function json_validate(string $json, int $depth = 512, int $flags = 0): bool { if ($flags !== 0 && $flags !== JSON_INVALID_UTF8_IGNORE) { throw new ValueError('json_validate(): Argument #3 ($flags) must be a valid flag (allowed flags: JSON_INVALID_UTF8_IGNORE)'); } if ($depth <= 0 ) { throw new ValueError('json_validate(): Argument #2 ($depth) must be greater than 0'); } json_decode($json, null, $depth, $flags); return json_last_error() === JSON_ERROR_NONE; } }
由于此函數(shù)內(nèi)部依然使用 json_decode,所以其實(shí)際上并沒有性能上的改進(jìn),只是提供了和 json_validate 相似的接口。
推薦學(xué)習(xí):《PHP視頻教程》