本文整理 PHP 核心語法與 JS 的主要差異,適合快速上手或查閱。
\n、\t、\\、\"、\$)。\\ 和 \'。define('CONST', 'value') 定義常數,**不可變**,在單/雙引號中**不會**被解析,需用串接:'value ' . CONST。<?php
$var = 'sofish';
echo "im $var"; // im sofish
echo 'im $var'; // im $var
define('NAME', 'sofish');
echo "im NAME"; // im NAME (常數不解析)
echo 'im ' . NAME; // im sofish
?>
$ 開頭,無需 var/let/const 關鍵字。$name ≠ $Name。array(...) 或 [...] (PHP 5.4+)。count()、shuffle()、array_keys()、array_values()、in_array()、isset($arr['key'])。<?php $arr = ['name' => 'sofish', 'age' => 25, 'gender' => 'male']; $arr[] = 'new'; // 自動鍵為 0 (若無數字鍵) 或 max+1 ?>
. (點號),**非** +。$full = 'Hello' . ' ' . 'World'; // Hello World
\n 為換行;單引號 '\n' 為字面兩字元。PHP_EOL。if / elseif / else (注意:elseif 為一詞,else if 亦可但較少用)。switch / case / default (使用 == 比較,注意 '' == 0 陷阱)。for / while / do-while / foreach。function name($param = 'default') { ... } 支援預設值。(function(){})();需先指派給變數再呼叫,或用 call_user_func。&:function(&$var)。global $var 導入全域變數 (不推薦濫用)。use ($var) 繼承外部變數 (預設傳值,加 & 為傳址)。<?php
$a = 'hello';
$fn = function() use ($a) { echo $a . ' world'; }; // 繼承 $a (傳值)
$fn(); // hello world
$fn2 = function() use (&$a) { $a = 'changed'; }; // 傳址
$fn2();
echo $a; // changed
?>
list($a, $b) = $arr; 解構陣列賦值給多變數。isset($var):檢查變數存在且非 null (比 array_key_exists 快)。is_array()、is_string()、is_int()、is_bool()、is_null() 等型別檢查。class Name { public $prop; public function method() {} }。$obj = new Name();。$obj->prop、$obj->method()。public、protected、private。static $prop、static function method(),用 Class::$prop、Class::method() 存取。