前端转后端基础- 变量和类型
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
PHP、Go、JavaScript三种语言在变量和类型相关的核心语法对照。 一、变量声明和赋值PHP 变量语法Go 变量语法JavaScript 变量语法二、数据类型详解PHP 数据类型<?php // 标量类型 // 整数类型 $int1 = 123; // 十进制 $int2 = -123; // 负数 $int3 = 0123; // 八进制(123) $int4 = 0x1A; // 十六进制(26) $int5 = 0b11111111; // 二进制(255) // 浮点数类型 $float1 = 1.234; $float2 = 1.2e3; // 1200 $float3 = 7E-10; // 0.0000000007 // 字符串类型 $string1 = '单引号字符串'; $string2 = "双引号字符串,可以包含变量 $name"; $string3 = "转义字符:\n 换行,\t 制表符"; $string4 = <<<EOT 多行字符串 Heredoc语法 EOT; // 布尔类型 $bool1 = true; $bool2 = false; $bool3 = (bool)1; // true $bool4 = (bool)0; // false $bool5 = (bool)"0"; // false $bool6 = (bool)""; // false $bool7 = (bool)null; // false // 复合类型 // 数组类型 $array1 = array(1, 2, 3); // 索引数组 $array2 = [1, 2, 3]; // 短数组语法 $array3 = ["a" => 1, "b" => 2]; // 关联数组 $array4 = [1, "a" => 2, 3]; // 混合数组 // 对象类型 class Person { public $name; public $age;
function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $obj = new Person("张三", 25); // 特殊类型 // NULL类型 $null1 = null; $null2 = NULL; $null3; // 未初始化的变量 // 资源类型 $file = fopen("test.txt", "r"); // $file 是一个资源类型 // 回调类型 function callback($param) { echo $param; } $cb = 'callback'; $cb("test"); // 类型声明 // 标量类型声明(PHP 7+) function add(int $a, int $b): int { return $a + $b; } function divide(float $a, float $b): float { return $a / $b; } function greet(string $name): string { return "Hello, $name"; } function isActive(bool $status): bool { return $status; } // 返回类型声明 function getArray(): array { return [1, 2, 3]; } function getObject(): Person { return new Person("李四", 30); } function getCallable(): callable { return function() { return "callable"; }; } // 可空类型 function nullable(?string $name): ?string { return $name; } // 联合类型(PHP 8+) function union(int|string $param): int|string { return $param; } // 交集类型(PHP 8.1+) function intersection(Traversable&Countable $param) { // ... } // 类型检查函数 $var = 123; var_dump(is_int($var)); // true var_dump(is_float($var)); // false var_dump(is_string($var)); // false var_dump(is_bool($var)); // false var_dump(is_array($var)); // false var_dump(is_object($var)); // false var_dump(is_null($var)); // false var_dump(is_numeric($var)); // true var_dump(is_scalar($var)); // true // 类型转换 // 显式转换 $int = (int)"123"; $float = (float)"3.14"; $string = (string)123; $bool = (bool)"true"; $array = (array)$obj; $object = (object)$array; // settype函数 $var = "123"; settype($var, "integer"); var_dump($var); // int(123) // 类型比较 var_dump(1 == "1"); // true (宽松比较) var_dump(1 === "1"); // false (严格比较) var_dump(0 == false); // true var_dump(0 === false); // false var_dump(null == 0); // true var_dump(null === 0); // false // 类型提示 class Container { private array $items = [];
public function addItem(string $item): void { $this->items[] = $item; }
public function getItems(): array { return $this->items; } } // 枚举类型(PHP 8.1+) enum Status: string { case DRAFT = 'draft'; case PUBLISHED = 'published'; case ARCHIVED = 'archived'; } $status = Status::PUBLISHED; echo $status->value; // "published" // 只读属性(PHP 8.1+) class User { public readonly string $name;
public function __construct(string $name) { $this->name = $name; } } // 新的初始化器(PHP 8.1+) class Product { public function __construct( private string $name, private float $price = 0.0, private array $tags = [] ) {} } // 属性类型 class Article { public string $title; public ?string $content = null; public array $metadata = []; public DateTime $createdAt; } // 泛型注释(虽然PHP没有原生泛型) /** * @template T * @param T $value * @return T */ function identity($value) { return $value; } ?> Go 数据类型JavaScript 数据类型代码高亮:
// 原始类型(Primitive Types) // 字符串类型 let str1 = "双引号字符串"; let str2 = '单引号字符串'; let str3 = `模板字符串,可以包含变量 ${name}`; let str4 = String(123); // 类型转换 let str5 = new String("对象字符串"); // 不推荐 // 数值类型 let num1 = 123; // 整数 let num2 = -456; // 负数 let num3 = 3.14; // 浮点数 let num4 = 1.23e4; // 科学计数法 12300 let num5 = 0xFF; // 十六进制 255 let num6 = 0o777; // 八进制 511 let num7 = 0b1111; // 二进制 15 let num8 = Infinity; // 无穷大 let num9 = -Infinity; // 负无穷大 let num10 = NaN; // 非数字 let num11 = Number.MAX_VALUE; // 最大数值 let num12 = Number.MIN_VALUE; // 最小数值 // 大整数类型(ES2020+) let bigInt1 = 123n; let bigInt2 = BigInt(123); let bigInt3 = BigInt("123456789012345678901234567890"); // 布尔类型 let bool1 = true; let bool2 = false; let bool3 = Boolean(1); // true let bool4 = Boolean(0); // false let bool5 = Boolean("hello"); // true let bool6 = Boolean(""); // false let bool7 = !!value; // 双重否定转换 // Undefined类型 let undef1; let undef2 = undefined; let undef3 = void 0; // 另一种写法 // Null类型 let null1 = null; // Symbol类型(ES2015+) let sym1 = Symbol("description"); let sym2 = Symbol("description"); console.log(sym1 === sym2); // false,唯一性 // 全局Symbol注册表 let globalSym1 = Symbol.for("global"); let globalSym2 = Symbol.for("global"); console.log(globalSym1 === globalSym2); // true // Symbol作为对象属性键 let obj = { [Symbol("key")]: "value", [Symbol.iterator]: function*() { yield 1; yield 2; } }; // 对象类型(Object Types) // 普通对象 let obj1 = {key: "value"}; let obj2 = new Object(); let obj3 = Object.create(null); // 无原型对象 // 数组 let arr1 = [1, 2, 3]; let arr2 = new Array(1, 2, 3); let arr3 = Array.of(1, 2, 3); let arr4 = Array.from("hello"); // ['h', 'e', 'l', 'l', 'o'] // 函数 function func1() {} let func2 = function() {}; let func3 = () => {}; let func4 = new Function('a', 'b', 'return a + b'); // 日期对象 let date1 = new Date(); let date2 = new Date(2024, 0, 1); // 2024年1月1日 let date3 = new Date("2024-01-01"); // 正则表达式 let regex1 = /pattern/; let regex2 = new RegExp("pattern"); let regex3 = /pattern/gi; // 全局、忽略大小写 // 错误对象 let error1 = new Error("错误信息"); let error2 = new TypeError("类型错误"); let error3 = new RangeError("范围错误"); // Map对象(ES2015+) let map = new Map(); map.set("key", "value"); map.set(1, "number"); map.set(true, "boolean"); // Set对象(ES2015+) let set = new Set(); set.add(1); set.add(2); set.add(2); // 重复值不会添加 set.add("string"); // WeakMap对象(ES2015+) let weakMap = new WeakMap(); let keyObj = {}; weakMap.set(keyObj, "value"); // WeakSet对象(ES2015+) let weakSet = new WeakSet(); weakSet.add(keyObj); // Promise对象(ES2015+) let promise = new Promise((resolve, reject) => { resolve("成功"); }); // Proxy对象(ES2015+) let target = {key: "value"}; let proxy = new Proxy(target, { get: function(obj, prop) { return prop in obj ? obj[prop] : "默认值"; } }); // Reflect对象(ES2015+) let objReflect = {}; Reflect.set(objReflect, 'key', 'value'); console.log(Reflect.get(objReflect, 'key')); // 类(ES2015+) class Person { constructor(name, age) { this.name = name; this.age = age; }
greet() { console.log(`Hello, ${this.name}`); } } // 静态方法和属性 class MyClass { static staticProp = "静态属性";
static staticMethod() { return "静态方法"; } } // 私有字段(ES2022+) class PrivateClass { #privateField = "私有字段";
getPrivate() { return this.#privateField; } } // 类型检查 let value = "hello"; console.log(typeof value); // "string" console.log(typeof 123); // "number" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined" console.log(typeof null); // "object" (历史遗留问题) console.log(typeof {}); // "object" console.log(typeof []); // "object" console.log(typeof function(){}); // "function" console.log(typeof Symbol()); // "symbol" console.log(typeof 123n); // "bigint" // instanceof 检查 console.log([] instanceof Array); // true console.log({} instanceof Object); // true console.log(function(){} instanceof Function); // true console.log(new Date() instanceof Date); // true // Array.isArray 检查 console.log(Array.isArray([])); // true console.log(Array.isArray({})); // false // Object.prototype.toString 检查 console.log(Object.prototype.toString.call([])); // "[object Array]" console.log(Object.prototype.toString.call({})); // "[object Object]" console.log(Object.prototype.toString.call(null)); // "[object Null]" console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]" // 类型转换 // 字符串转换 let strNum = String(123); let strBool = String(true); let strObj = String({key: "value"}); let strNull = String(null); let strUndef = String(undefined); // 数字转换 let numStr = Number("123"); let numBool = Number(true); let numObj = Number({valueOf: () => 42}); let numParseInt = parseInt("123"); let numParseFloat = parseFloat("3.14"); // 布尔转换 let boolStr = Boolean("hello"); let boolNum = Boolean(0); let boolObj = Boolean({}); let boolArr = Boolean([]); // 隐式类型转换 let result1 = "5" + 3; // "53" (字符串拼接) let result2 = "5" - 3; // 2 (数字减法) let result3 = "5" * 3; // 15 (数字乘法) let result4 = "5" / 2; // 2.5 (数字除法) let result5 = "5" % 2; // 1 (数字取模) // == 和 === 的区别 console.log(5 == "5"); // true (类型转换后比较) console.log(5 === "5"); // false (类型和值都比较) console.log(0 == false); // true console.log(0 === false); // false console.log(null == undefined); // true console.log(null === undefined); // false // 类型转换规则 // ToPrimitive - 转换为原始值 let objToPrim = { valueOf: function() { return 42; }, toString: function() { return "hello"; } }; console.log(+objToPrim); // 42 (优先调用valueOf) // ToNumber - 转换为数字 console.log(Number("123")); // 123 console.log(Number("3.14")); // 3.14 console.log(Number("")); // 0 console.log(Number("hello")); // NaN console.log(Number(true)); // 1 console.log(Number(false)); // 0 console.log(Number(null)); // 0 console.log(Number(undefined)); // NaN // ToString - 转换为字符串 console.log(String(123)); // "123" console.log(String(true)); // "true" console.log(String(null)); // "null" console.log(String(undefined)); // "undefined" console.log(String({})); // "[object Object]" // ToBoolean - 转换为布尔值 // 以下值转换为false console.log(Boolean(false)); // false console.log(Boolean(0)); // false console.log(Boolean(-0)); // false console.log(Boolean(0n)); // false console.log(Boolean("")); // false console.log(Boolean(null)); // false console.log(Boolean(undefined)); // false console.log(Boolean(NaN)); // false // 其他所有值转换为true console.log(Boolean("0")); // true console.log(Boolean("false")); // true console.log(Boolean([])); // true console.log(Boolean({})); // true console.log(Boolean(function(){})); // true // 类型安全函数 function safeAdd(a, b) { if (typeof a !== 'number' || typeof b !== 'number') { throw new TypeError('参数必须是数字'); } return a + b; } // TypeScript类型注释(虽然不是原生支持) /** * @param {number} a * @param {number} b * @returns {number} */ function add(a, b) { return a + b; } // JSDoc类型注释 /** * @typedef {Object} User * @property {string} name * @property {number} age * @property {string[]} hobbies */ /** * @param {User} user * @returns {string} */ function greetUser(user) { return `Hello, ${user.name}`; } // 类型守卫 function isString(value) { return typeof value === 'string'; } function process(value) { if (isString(value)) { // TypeScript中这里value会被推断为string类型 return value.toUpperCase(); } return value; } 以上是三种语言在变量和类型方面的详细对照,涵盖了基本语法、数据类型、类型转换、作用域等核心概念。每种语言都有其独特的特性和最佳实践。 参考文章:原文链接 该文章在 2026/4/3 10:25:18 编辑过 |
关键字查询
相关文章
正在查询... |