这份 PHP 备忘单为快速查找最常用代码的正确语法提供了参考
入门 hello.php 1 2 3 4 <?php echo "Hello World\n" ;print ("Hello jaywcjlove.github.io" );?>
PHP 运行命令
变量 Variables 1 2 3 4 5 6 7 $boolean1 = true ;$boolean2 = True;$int = 12 ;$float = 3.1415926 ;unset ($float ); $str1 = "How are you?" ;$str2 = 'Fine, thanks' ;
查看: Types
字符串 Strings 1 2 3 4 5 6 7 $url = "jaywcjlove.github.io" ;echo "I'm learning PHP at $url " ;echo "I'm learning PHP at " . $url ;$hello = "Hello, " ;$hello .= "World!" ;echo $hello ;
查看: Strings
数组 Arrays 1 2 3 4 5 $num = [1 , 3 , 5 , 7 , 9 ];$num [5 ] = 11 ;unset ($num [2 ]); print_r ($num ); echo count ($num );
查看: Arrays
运算符 Operators 1 2 3 4 $x = 1 ;$y = 2 ;$sum = $x + $y ;echo $sum ;
查看: Operators
Include vars.php 1 2 3 4 5 <?php $fruit = 'apple' ;echo "I was imported" ;return 'Anything you like.' ;?>
test.php 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?php include 'vars.php' ;echo $fruit . "\n" ; require 'vars.php' ;include ('vars.php' );require ('vars.php' );include 'http://x.com/file.php' ;$result = include 'vars.php' ;echo $result ; ?>
功能 Functions 1 2 3 4 5 function add ($num1 , $num2 = 1 ) { return $num1 + $num2 ; } echo add (10 ); echo add (10 , 5 );
查看: Functions
常数 Constants 1 2 3 4 5 const MY_CONST = "hello" ;echo MY_CONST; echo 'MY_CONST is: ' . MY_CONST;
类 Classes 1 2 3 4 5 6 class Student { public function __construct ($name ) { $this ->name = $name ; } } $alex = new Student ("Alex" );
查看: Classes
PHP 类型 布尔值 Boolean 1 2 3 4 5 6 $boolean1 = true ;$boolean2 = TRUE ;$boolean3 = false ;$boolean4 = FALSE ;$boolean5 = (boolean ) 1 ; $boolean6 = (boolean ) 0 ;
布尔值不区分大小写
整数 Integer 1 2 3 4 5 6 7 $int1 = 28 ; $int2 = -32 ; $int3 = 012 ; $int4 = 0x0F ; $int5 = 0b101 ; $int6 = 2_000_100_000 ;
另见: Integers
字符串 Strings 1 echo 'this is a simple string' ;
查看: Strings
数组 Arrays 1 $arr = array ("hello" , "world" , "!" );
查看: Arrays
浮点数 Float (Double) 1 2 3 4 5 6 7 $float1 = 1.234 ;$float2 = 1.2e7 ;$float3 = 7E-10 ;$float4 = 1_234.567 ; var_dump ($float4 ); $float5 = 1 + "10.5" ; $float6 = 1 + "-1.3e3" ;
Null 1 2 3 4 5 6 7 8 $a = null ;$b = 'Hello php!' ;echo $a ?? 'a is unset' ; echo $b ?? 'b is unset' ; $a = array ();$a == null $a === null is_null ($a )
可迭代对象 Iterables 1 2 3 4 5 6 7 8 9 10 11 function bar ( ): iterable { return [1 , 2 , 3 ]; } function gen ( ): iterable { yield 1 ; yield 2 ; yield 3 ; } foreach (bar () as $value ) { echo $value ; }
PHP 字符串 字符串 String 1 2 3 4 5 6 7 8 $sgl_quotes = '$String' ;$dbl_quotes = "This is a $sgl_quotes ." ;$escaped = "a \t tab character." ;$unescaped = 'a slash and a t: \t' ;
多行 Multi-line 1 2 3 4 5 6 7 8 9 10 11 $str = "foo" ;$nowdoc = <<<'END' Multi line string $str END; $heredoc = <<<END Multi line $str END ;
操作 Manipulation 1 2 3 4 5 6 7 8 9 $s = "Hello Phper" ;echo strlen ($s ); echo substr ($s , 0 , 3 ); echo substr ($s , 1 ); echo substr ($s , -4 , 3 );echo strtoupper ($s ); echo strtolower ($s ); echo strpos ($s , "l" ); var_dump (strpos ($s , "L" ));
另见: 字符串函数
PHP 数组 定义 1 2 3 $a1 = ["hello" , "world" , "!" ]$a2 = array ("hello" , "world" , "!" );$a3 = explode ("," , "apple,pear,peach" );
混合 int 和 string 键 1 2 3 4 5 6 7 $array = array ( "foo" => "bar" , "bar" => "foo" , 100 => -100 , -100 => 100 , ); var_dump ($array );
短数组语法 1 2 3 4 $array = [ "foo" => "bar" , "bar" => "foo" , ];
多阵列 1 2 3 4 5 6 7 8 $multiArray = [ [1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 9 ], ]; print_r ($multiArray [0 ][0 ]) print_r ($multiArray [0 ][1 ]) print_r ($multiArray [0 ][2 ])
多类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 $array = array ( "foo" => "bar" , 42 => 24 , "multi" => array ( "dim" => array ( "a" => "foo" ) ) ); var_dump ($array ["foo" ]);var_dump ($array [42 ]); var_dump ($array ["multi" ]["dim" ]["a" ]);
操作 1 2 3 4 5 6 $arr = array (5 => 1 , 12 => 2 );$arr [] = 56 ; $arr ["x" ] = 42 ; sort ($arr ); unset ($arr [5 ]); unset ($arr );
查看: 数组函数
索引迭代 1 2 3 4 5 $array = array ('a' , 'b' , 'c' );$count = count ($array );for ($i = 0 ; $i < $count ; $i ++) { echo "i:{$i} , v:{$array[$i]} \n" ; }
价值迭代 1 2 3 4 $colors = array ('red' , 'blue' , 'green' );foreach ($colors as $color ) { echo "Do you like $color ?\n" ; }
关键迭代 1 2 3 4 5 6 $arr = ["foo" => "bar" , "bar" => "foo" ];foreach ( $arr as $key => $value ){ echo "key: " . $key . "\n" ; echo "val: {$arr[$key]} \n" ; }
串联阵列 1 2 3 4 5 $a = [1 , 2 ];$b = [3 , 4 ];$result = [...$a , ...$b ];
Into 函数 1 2 3 4 5 6 $array = [1 , 2 ];function foo (int $a , int $b ) { echo $a ; echo $b ; } foo (...$array );
Splat运算符 1 2 3 4 5 6 7 function foo ($first , ...$other ) { var_dump ($first ); var_dump ($other ); } foo ('a' , 'b' , 'c' );function foo ($first , string ...$other ) {}
PHP 运算符 算术
:-
-
+
添加
-
减法
*
乘法
/
分配
%
取模
**
求幂
分配
:-
-
a += b
如同 a = a + b
a -= b
如同 a = a – b
a *= b
如同 a = a * b
a /= b
如同 a = a / b
a %= b
如同 a = a % b
比较
:-
-
==
平等的
===
完全相同的
!=
不相等
<>
不相等
!==
不相同
<
少于
>
比…更棒
<=
小于或等于
>=
大于或等于
<=>
小于/等于/大于
逻辑的
:-
-
and
和
or
或者
xor
独家或
!
不是
&&
和
||
或者
算术 1 2 3 4 5 6 7 8 9 10 11 $sum = 1 + 1 ; $difference = 2 - 1 ; $product = 2 * 2 ; $quotient = 2 / 1 ; $num = 0 ;$num += 1 ; echo $num ++; echo ++$num ; $num /= $float ;
按位
:-
-
&
和
`
`
^
异或(异或)
~
不是
<<
左移
>>
右移
PHP 条件 If elseif else 1 2 3 4 5 6 7 8 9 $a = 10 ;$b = 20 ;if ($a > $b ) { echo "a is bigger than b" ; } elseif ($a == $b ) { echo "a is equal to b" ; } else { echo "a is smaller than b" ; }
Switch 1 2 3 4 5 6 7 8 9 10 11 12 $x = 0 ;switch ($x ) { case '0' : print "it's zero" ; break ; case 'two' : case 'three' : break ; default : }
三元运算符 1 2 3 4 5 6 7 8 9 10 11 print (false ? 'Not' : 'Does' );$x = false ;print ($x ?: 'Does' );$a = null ;$b = 'Does print' ;echo $a ?? 'a is unset' ;echo $b ?? 'b is unset' ;
匹配 1 2 3 4 5 6 7 8 $statusCode = 500 ;$message = match ($statusCode ) { 200 , 300 => null , 400 => '未找到' , 500 => '服务器错误' , default => '已知状态码' , }; echo $message ;
查看: Match
匹配表达式 1 2 3 4 5 6 7 8 $age = 23 ;$result = match (true ) { $age >= 65 => 'senior' , $age >= 25 => 'adult' , $age >= 18 => 'young adult' , default => 'kid' , }; echo $result ;
PHP 循环 while 循环 1 2 3 4 5 $i = 1 ;while ($i <= 5 ) { echo $i ++; }
do while 循环 1 2 3 4 5 $i = 1 ;do { echo $i ++; } while ($i <= 5 );
for i 循环 1 2 3 4 for ($i = 1 ; $i <= 5 ; $i ++) { echo $i ; }
break 跳出循环 1 2 3 4 5 6 7 for ($i = 1 ; $i <= 5 ; $i ++) { if ($i === 4 ) { break ; } echo $i ; }
continue 继续 1 2 3 4 5 6 7 for ($i = 1 ; $i <= 5 ; $i ++) { if ($i === 4 ) { continue ; } echo $i ; }
foreach 循环 1 2 3 4 5 $a = ['foo' => 1 , 'bar' => 2 ];foreach ($a as $k ) { echo $k ; }
查看: Array iteration
PHP 函数 返回值 1 2 3 4 5 function square ($x ) { return $x * $x ; } echo square (4 );
返回类型 1 2 3 4 5 6 function sum ($a , $b ): float {}function get_item ( ): string {}class C {}function getC ( ): C { return new C; }
可空返回类型 1 2 3 4 5 6 7 function nullOrString (int $v ) : ?string { return $v % 2 ? "odd" : null ; } echo nullOrString (3 ); var_dump (nullOrString (4 ));
查看: Nullable types
无效函数 1 2 3 4 5 6 7 function voidFunction ( ): void { echo 'Hello' ; return ; } voidFunction ();
变量函数 1 2 3 4 5 6 function bar ($arg = '' ) { echo "In bar(); arg: '$arg '.\n" ; } $func = 'bar' ;$func ('test' );
匿名函数 1 2 3 4 5 6 $greet = function ($name ) { printf ("Hello %s\r\n" , $name ); }; $greet ('World' ); $greet ('PHP' );
递归函数 1 2 3 4 5 6 7 8 function recursion ($x ) { if ($x < 5 ) { echo "$x " ; recursion ($x + 1 ); } } recursion (1 );
默认参数 1 2 3 4 5 6 7 8 9 10 function coffee ($type = "cappuccino" ) { return "Making a cup of $type .\n" ; } echo coffee ();echo coffee (null );echo coffee ("espresso" );
箭头函数 1 2 3 4 5 6 7 8 9 $y = 1 ; $fn1 = fn ($x ) => $x + $y ;$fn2 = function ($x ) use ($y ) { return $x + $y ; }; echo $fn1 (5 ); echo $fn2 (5 );
PHP 类 构造函数 Constructor 1 2 3 4 5 6 7 8 9 10 class Student { public function __construct ($name ) { $this ->name = $name ; } public function print ( ) { echo "Name: " . $this ->name; } } $alex = new Student ("Alex" );$alex ->print ();
继承 Inheritance 1 2 3 4 5 6 7 8 9 10 11 class ExtendClass extends SimpleClass { function displayVar ( ) { echo "Extending class\n" ; parent ::displayVar (); } } $extended = new ExtendClass ();$extended ->displayVar ();
类变量 Classes variables 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class MyClass { const MY_CONST = 'value' ; static $staticVar = 'static' ; public static $var1 = 'pubs' ; private static $var2 = 'pris' ; protected static $var3 = 'pros' ; protected $var6 = 'pro' ; private $var7 = 'pri' ; }
静态访问
1 2 echo MyClass ::MY_CONST ; echo MyClass ::$staticVar ;
魔术方法 1 2 3 4 5 6 7 8 9 10 11 12 13 class MyClass { public function __toString ( ) { return $property ; } public function __destruct ( ) { print "Destroying" ; } }
接口 1 2 3 4 5 6 7 8 9 10 11 12 13 interface Foo { public function doSomething ( ) ; } interface Bar { public function doSomethingElse ( ) ; } class Cls implements Foo , Bar { public function doSomething ( ) {} public function doSomethingElse ( ) {} }
各种各样的 基本错误处理 1 2 3 4 5 6 7 try { } catch (Exception $e ) { } finally { echo "Always print!" ; }
PHP 8.0 中的异常 {.wrap} 1 2 3 4 5 6 7 $nullableValue = null ;try { $value = $nullableValue ?? throw new InvalidArgumentException (); } catch (InvalidArgumentException ) { echo "print me!" ; }
自定义异常 1 2 3 class MyException extends Exception { }
用法
1 2 3 4 5 6 7 8 try { $condition = true ; if ($condition ) { throw new MyException ('bala' ); } } catch (MyException $e ) { }
Nullsafe 运算符 1 2 3 4 5 6 7 8 9 10 11 12 13 $result = $repo ?->getUser (5 )?->name;if (is_null ($repo )) { $result = null ; } else { $user = $repository ->getUser (5 ); if (is_null ($user )) { $result = null ; } else { $result = $user ->name; } }
另见: Nullsafe 运算符
常用表达 1 2 $str = "Visit jaywcjlove.github.io" ;echo preg_match ("/qu/i" , $str );
查看: PHP中的正则表达式
fopen() 模式
:-
-
r
读
r+
读写,前置
w
写入,截断
w+
读写,截断
a
写,追加
a+
读写,追加
运行时定义的常量 1 2 3 4 5 define ("CURRENT_DATE" , date ('Y-m-d' ));echo CURRENT_DATE; echo 'CURRENT_DATE is: ' . CURRENT_DATE;
另见