<?php declare(strict_types=1); ini_set('display_errors', 'On'); error_reporting(-1); /** * 打印变量的相关信息 * * @param mixed $value 要打印的表达式 * @param mixed ...$values 更多要打印的表达式 * @return void echo */ function v(mixed $value, mixed ...$values): void { ob_start(); // 打开输出控制缓冲 var_dump($value); echo ob_get_clean(); // 从缓冲区获取var_dump()的内容,然后清空缓冲区 foreach ($values as $v) { v($v); // 递归 } } /** * Json类 */ class Json { /** * 对变量进行JSON编码 * * @param mixed $value 待编码的value,除了resource类型之外,可以为任何数据类型 * @return string|false 成功则返回JSON编码的string或者在失败时返回false */ public static function encode(mixed $value): string|false { $encode = false; try { $encode = json_encode($value, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } catch (JsonException $e) { unset($e); } return $encode; } /** * 对JSON格式的字符串进行解码 * * @param string $json 待解码的json string格式的字符串 * @return mixed 返回编码的数据,若解码失败将会返回null */ public static function decode(string $json): mixed { $decode = null; try { $decode = json_decode($json, true, 512, JSON_THROW_ON_ERROR); } catch (JsonException $e) { unset($e); } return $decode; } } $profile = ['name' => '张三', 'gender' => '男', 'birth' => 2003]; $encode = Json::encode($profile); v($encode); // string(45) "{"name":"张三","gender":"男","birth":2003}" $decode = Json::decode($encode); v($decode); // array(3) { ["name"]=> string(6) "张三" ["gender"]=> string(3) "男" ["birth"]=> int(2003) }
Copyright © 2024 码农人生. All Rights Reserved