开发手册 欢迎您!
软件开发者资料库

PHP 备忘录

此PHP备忘单提供了一个参考,可用于快速查找您最常使用的代码的正确语法。开始hello.php<?php//beginwithaPHPopentag.echo"HelloWorld\n";print("Helloquickref.me");?>PHP运行命令$phphello.php变量

PHP备忘单提供了一个参考,可用于快速查找您最常使用的代码的正确语法。

开始

hello.php


PHP运行命令

$ php hello.php

变量

$boolean1 = true;
$boolean2 = True;

$int = 12;
$float = 3.1415926;
unset($float);  // Delete variable

$str1 = "How are you?";
$str2 = 'Fine, thanks';

请参阅:类型

Include

变量文件


测试文件

 apple

/* Same as include,
cause an error if cannot be included*/
require 'vars.php';

// Also works
include('vars.php');
require('vars.php');

// Include through HTTP
include 'http://x.com/file.php';

// Include and the return statement
$result = include 'vars.php';
echo $result;  # => Anything you like.
?>

注释

# This is a one line shell-style comment

// This is a one line c++ style comment

/* This is a multi line comment
   yet another line of comment */

常数

const MY_CONST = "hello";

echo MY_CONST;   # => hello

# => MY_CONST is: hello
echo 'MY_CONST is: ' . MY_CONST; 

PHP 字符串

String

# => '$String'
$sgl_quotes = '$String';

# => 'This is a $String.'
$dbl_quotes = "This is a $sgl_quotes.";

# => a  tab character.
$escaped   = "a \t tab character.";

# => a slash and a t: \t
$unescaped = 'a slash and a t: \t';

Multi line

$str = "foo";

// Uninterpolated multi-liners
$nowdoc = <<<'END'
Multi line string
$str
END;

// Will do string interpolation
$heredoc = <<

操作

$s = "Hello Phper";
echo strlen($s);       # => 11

echo substr($s, 0, 3); # => Hel
echo substr($s, 1);    # => ello Phper
echo substr($s, -4, 3);# => hpe

echo strtoupper($s);   # => HELLO PHPER
echo strtolower($s);   # => hello phper

echo strpos($s, "l");      # => 2
var_dump(strpos($s, "L")); # => false

请参阅:字符串函数

PHP 数组

定义

$a1 = ["hello", "world", "!"]
$a2 = array("hello", "world", "!");
$a3 = explode(",", "apple,pear,peach");

混合 int 和 string 键

$array = array(
    "foo" => "bar",
    "bar" => "foo",
    100   => -100,
    -100  => 100,
);
var_dump($array);

短数组语法

$array = [
    "foo" => "bar",
    "bar" => "foo",
];

多维度

$multiArray = [ 
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];

print_r($multiArray[0][0]) # => 1
print_r($multiArray[0][1]) # => 2
print_r($multiArray[0][2]) # => 3

多类型

$array = array(
    "foo" => "bar",
    42    => 24,
    "multi" => array(
         "dim" => array(
             "a" => "foo"
         )
    )
);

# => string(3) "bar"
var_dump($array["foo"]);

# => int(24)
var_dump($array[42]);    

# =>  string(3) "foo"
var_dump($array["multi"]["dim"]["a"]);

操作

$arr = array(5 => 1, 12 => 2);
$arr[] = 56;      // Append
$arr["x"] = 42;   // Add with key
sort($arr);       // Sort
unset($arr[5]);   // Remove
unset($arr);      // Remove all

请参阅:数组函数

索引迭代

$array = array('a', 'b', 'c');
$count = count($array);

for ($i = 0; $i < $count; $i++) {
    echo "i:{$i}, v:{$array[$i]}\n";
}

值迭代

$colors = array('red', 'blue', 'green');

foreach ($colors as $color) {
    echo "Do you like $color?\n";
}

关键迭代

$arr = ["foo" => "bar", "bar" => "foo"];

foreach ( $arr as $key => $value )
{
  echo "key: " . $key . "\n";
    echo "val: {$arr[$key]}\n";
}

串联数组

$a = [1, 2];
$b = [3, 4];

// PHP 7.4 later
# => [1, 2, 3, 4]
$result = [...$a, ...$b];

函数调用

$array = [1, 2];

function foo(int $a, int $b) {
echo $a; # => 1
  echo $b; # => 2
}
foo(...$array);

Splat 操作符

function foo($first, ...$other) {
var_dump($first); # => a
  var_dump($other); # => ['b', 'c']
}
foo('a', 'b', 'c' /*, ...*/ );
// or
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 独占或
! 不是
&&
|| 或者

算术

// Arithmetic
$sum        = 1 + 1; // 2
$difference = 2 - 1; // 1
$product    = 2 * 2; // 4
$quotient   = 2 / 1; // 2

// Shorthand arithmetic
$num = 0;
$num += 1;       // Increment $num by 1
echo $num++;     // Prints 1 (increments after evaluation)
echo ++$num;     // Prints 3 (increments before evaluation)
$num /= $float;  // Divide and assign the quotient to $num

&
| 或(包括或)
^ Xor(异或)
~ 不是
<< 左移
>> 右移

PHP 条件

if else

$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

$x = 0;
switch ($x) {
    case '0':
        print "it's zero";
        break; 
    case 'two':
    case 'three':
        // do something
        break;
    default:
        // do something
}

三元运算符

# => Does
print (false ? 'Not' : 'Does');

$x = false;
# => Does
print($x ?: 'Does');

$a = null;
$b = 'Does print';
# => a is unsert
echo $a ?? 'a is unset';
# => print
echo $b ?? 'b is unset';

匹配

$statusCode = 500;
$message = match($statusCode) {
  200, 300 => null,
  400 => 'not found',
  500 => 'server error',
  default => 'known status code',
};
echo $message; # => server error

参见:匹配

匹配表达式

$age = 23;

$result = match (true) {
    $age >= 65 => 'senior',
    $age >= 25 => 'adult',
    $age >= 18 => 'young adult',
    default => 'kid',
};

echo $result; # => young adult

PHP 函数

返回值

function square($x)
{
    return $x * $x;
}

echo square(4);  # => 16

返回类型

// Basic return type declaration
function sum($a, $b): float {/*...*/}
function get_item(): string {/*...*/}

class C {}
// Returning an object
function getC(): C { return new C; }

可空返回类型

// Available in PHP 7.1
function nullOrString(int $v) : ?string
{
    return $v % 2 ? "odd" : null;
}
echo nullOrString(3);       # => odd
var_dump(nullOrString(4));  # => NULL

请参阅:可空类型

空函数

// Available in PHP 7.1
function voidFunction(): void
{
echo 'Hello';
return;
}

voidFunction();  # => Hello

变量函数

function bar($arg = '')
{
    echo "In bar(); arg: '$arg'.\n";
}

$func = 'bar';
$func('test'); # => In bar(); arg: test

匿名函数

$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World'); # => Hello World
$greet('PHP');   # => Hello PHP

递归函数

function recursion($x)
{
    if ($x < 5) {
        echo "$x";
        recursion($x + 1);
    }
}
recursion(1);  # => 1234

默认参数

function coffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
# => Making a cup of cappuccino.
echo coffee();
# => Making a cup of .
echo coffee(null);
# => Making a cup of espresso.
echo coffee("espresso");

箭头函数

$y = 1;
 
$fn1 = fn($x) => $x + $y;

// equivalent to using $y by value:
$fn2 = function ($x) use ($y) {
    return $x + $y;
};
echo $fn1(5);   # => 6
echo $fn2(5);   # => 6

PHP 类

构造函数

class Student {
    public function __construct($name) {
        $this->name = $name;
    }
  public function print() {
        echo "Name: " . $this->name;
    }
}
$alex = new Student("Alex");
$alex->print();    # => Name: Alex

继承

class ExtendClass extends SimpleClass
{
    // Redefine the parent method
    function displayVar()
    {
        echo "Extending class\n";
        parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();

类变量

class MyClass
{
    const MY_CONST       = 'value';
    static $staticVar    = 'static';

    // Visibility
    public static $var1  = 'pubs';

    // Class only
    private static $var2 = 'pris';

    // The class and subclasses
    protected static $var3 = 'pros';

    // The class and subclasses
    protected $var6      = 'pro';

    // The class only
    private $var7        = 'pri';  
}

静态访问

echo MyClass::MY_CONST;   # => value
echo MyClass::$staticVar; # => static

魔术方法

class MyClass
{
    // Object is treated as a String
    public function __toString()
    {
        return $property;
    }
    // opposite to __construct()
    public function __destruct()
    {
        print "Destroying";
    }
}

接口

interface Foo 
{
    public function doSomething();
}
interface Bar
{
    public function doSomethingElse();
}
class Cls implements Foo, Bar 
{
    public function doSomething() {}
    public function doSomethingElse() {}
}

另见

  • PHP 文档
  • 在 Y 分钟内学习 X