我钟爱的 PHP 速查表

关注我!: 关注 @EricTheCoder_


这是我在学习过程中创建的备忘单. 如果您有任何建议 (加/减) 请告诉我.


PHP 本地服务器

php -S localhost:3000

注释

// 单行注释

/*
这是一个多行注释块
跨越多行
*/

命名约定

// PHP 开始/结束 标记
<?php
  echo "Hello World";
?>
// 如果没有结束标记,文件的其余部分将被视为 PHP 代码

// 简短的 PHP 语法输出
<?= "Hello World" ?>

//启用严格模式 (它必须在 PHP 文件的第一行)
<? declare(strict_types=1);

// 包括一个 PHP 文件
require 'app/Product.php'

// 创建命名空间
namespace App;

// 使用命名空间
use App\Product;

$firstName = 'Mike'  // 小驼峰命名
function updateProduct() // 小驼峰命名
class ProductItem // 大驼峰命名
const ACCESS_KEY = '123abc'; // 所有大写字母用下划线分隔

输出 & 输入

echo 'Hello World';

// 调式输出
var_dump($names);
print_r($products);

// 从控制台输入
$name = readline('What is your name : ');

变量声明

$name = 'Mike'; //字符串
$isActive = true; //布尔型
$number = 25; //整型
$amount = 99.95; //浮点型
$fruits = ['orange', 'apple', 'banana'] //数组
const MAX_USERS = 50; //常量
define('MAX_USERS', 50); //常量

// 赋值 '引用' 是通过 & 关键字
$name_2 = &$name_1

// 类型转换
$age = (int)readline('Your age: ');
echo 'Your age is' . (string)$age;

echo gettype($age); // int

echo is_int($age) // true
echo is_float(12.5) // true
echo is_string($name) // true

字符串

// 字符串可以使用单引号
$name = 'Mike'
// 或双引号
$name = "Mike"

// 双引号字符串能够使用转义字符 \n = new line  \t = tab  \\ = backslash
echo "Hello Mike\nHello David";

// 双引号字符串能够插入变量
echo "Hello $name";

// 字符串拼接
echo 'Hello ' . $name;

// 字符串长度
echo strlen($name);

// 删除首部和尾部的空格
echo trim($text)

// 转换为小写 / 大写
echo strtolower($email);
echo strtoupper($name);

// 将第一个字符转换为大写
echo ucfirst($name);  // 'Mike' 

// 将 $text 中的文本 a 替换成文本 b
echo str_replace('a', 'b', $text);

// 字符串包含 (PHP 8)
echo str_contains($name, 'ke')  # true

// 查找 "k" 在字符串中第一次出现的位置
$pos = strpos($name, 'k'); # 2

// 返回字符串的一部分 (偏移量 / 长度)
echo substr($name, 0, $pos); # Mi 

数字


// 快捷增加并赋值
$value = 10
$value++ // 11
// or
$value += 1 // 11

// 快捷减少并赋值
$value = 10
$value-- // 9
// or
$value -= 1 // 9

// 检查是否是数字
echo is_numeric('59.99'); # true

// 四舍五入
echo round(0.80);  // returns 1

// 精确地对数字进行四舍五入
echo round(1.49356, 2));  // returns 1.49

// 随机数
echo(rand(10, 100)); # 89

条件语句

// If / elseif / else
if ($condition == 10) {
    echo 'condition 10'
} elseif  ($condition == 5) {
    echo 'condition 5'
} else {
    echo 'all other conditions'
}

// And 等于 &&
if ($condition === 10 && $condition2 === 5) {
    echo '10 and 5'
}

// Or 等于 ||
if ($condition === 10 || $condition2 === 5) {
    echo '10 or 5'
}

// 单行
if ($isActive) return true;

// 检查 null 值
if (is_null($name)) {
    do something...
}

// 比较操作符
== // 松散比较
=== // 严格比较
!= // 不等于
|| // 或
&& // 且
> // 大于
< // 小于

// 三元运算 (true : false)
echo $isValid ? 'user valid' : 'user not valid';

//Null 合并运算
echo $name ?? 'Mike';  //output 'Mike' if $name is null

//Null 合并赋值
$name ??= 'Mike';

// NULL 安全运算符(PHP 8)如果有一个?为 null,将返回 null
echo $user?->profile?->activate();

// Null 安全 + Null 合并 (如果为 null 将返回 『No user profile』)
echo $user?->profile?->activate() ?? 'Not applicable';

// 飞船符号 返回 -1 0 1
$names = ['Mike', 'Paul', 'John']
usort($names, function($a, $b) {
    return $a <=> $b;
}
// ['John', 'Mike', 'Paul']

// 转换为布尔值时返回 false
false, 0, 0.0, null, unset, '0', '', []

// 将同一变量与多个值进行比较
switch ($color) {
    case 'red':
        echo 'The color is red';
         break;
    case 'yellow':
        echo 'The color is yellow';
        break;
    case 'red':
        echo 'The color is red';
        break;
    default:
        echo 'The color is unknown';
}

// Match 表达式(PHP 8)
$type = match($color) {
    'red' => 'danger',
    'yellow', 'orange' => 'warning',
    'green' => 'success',
    default => 'Unknown'
};

// 检查变量是否声明
isset($color['red']);  # true

循环和迭代

// for 循环
for ($i = 0; $i < 20; $i++) {
    echo "i value = " . i;
}

// while 循环
$number = 1;
while ($number < 10) {
    echo 'value : ' . $number ;
    $number += 1;
}

//do while
$number = 1;
do {
    echo 'value : ' . $number ;
    $number += 1;
} while ($number < 10);

// foreach 带有 break / continue 的示例
$values = ['one', 'two', 'three'];
foreach ($values as $value) {
    if ($value === 'two') {
        break; // 退出循环
    } elseif ($value === 'three') {
        continue; // 下一个循环迭代
    }
}

数组

// 数组声明可以包含任何类型
$example = ['Mike', 50.2, true, ['10', '20'];

// 数组声明
$names = ['Mike', 'Peter', 'Shawn', 'John'];

// 直接访问特定元素
$name[1] //output Peter

// 如何访问数组中的数组元素
$example[3][1] // 20

// 将元素添加到数组
$names[] = 'Micheal';

// 数组合并
$array3 = array_merge($array1, $array2);

// 使用扩展运算符来进行数组合并
$names = ['Mike', 'Peter', 'Paul'];
$people = ['John', ...$names]; // ['John', 'Mike', 'Peter', 'Paul']

// 删除数组元素
unset($names['Peter']);

// 数组转字符串
echo implode(', ', $names) // 输出 Mike, Shawn, John, Micheal

// 字符串转数组
echo explode(',', $text); // ['Mike', 'Shawn', 'John']

// 遍历数组元素
foreach($names as $name) { 
   echo 'Hello ' . $name;
}

// 数组中元素的个数
echo count($names);  

// 关联数组声明 (key => value):
$person = ['age' => 45, 'genre' => 'men'];

// 添加到末尾. 数组:
$person['name'] = 'Mike';

// 循环数组 key => value: 
foreach($names as $key => $value) { 
   echo $key . ' : ' . $value
}

// 检查是否存在某个特定键
echo array_key_exists('age', $person);

// 返回键
echo array_keys($person); // ['age', 'genre']

// 返回值
echo array_values($person) // [45, 'men']

// 数组过滤器 (返回过滤后的数组)
$filteredPeople = array_filter($people, function ($person) {
    return $names->active;
})

// 数组映射 (返回变换后的数组):
$onlyNames = array_map(function($person) {
    return ['name' => $person->name];
}, $people)

# 搜索关联数组
$items = [
        ['id' => '100', 'name' => 'product 1'],
        ['id' => '200', 'name' => 'product 2'],
        ['id' => '300', 'name' => 'product 3'],
        ['id' => '400', 'name' => 'product 4'],
    ];

# 在 'name' 列中搜索所有值
$found_key = array_search('product 3', array_column($items, 'name'));
# 返回 2

函数

// 函数声明
function name($firstName, $lastName = 'defaultvalue') {
    return "$firstName $lastName"
}

// 函数调用
name('Mike', 'Taylor');

// 带命名参数的函数调用 (PHP 8)
name(firstName: 'Mike', lastName: 'Taylor'); // 排序能够改变

// 函数可变数量参数
function name(...$params) {
    return $params[0] . “ “ . params[1];
}

// 闭包函数
Route::get('/', function () {
     return view('welcome');
});

// 箭头函数
Route::get('/', fn () => view('welcome');

// 参数类型和返回类型
function display(string $first, string $last) : string {
    return "$first $last";
}

// 类型或空值
function display(?string $name) {
    ...
}

文件

// 获取当前目录
$current_dir = __DIR__;

// 检查文件是否存在
if (file_exists('/posts/first.txt')) {
  do some stuff
}

// 读取文件内容到一个变量中
$post = file_get_contents($file);

// 文件读取
$file = fopen("test.txt", "r");

// 输出行, 直到 EOF 结束
while(! feof($file)) {
  $line = fgets($file);
  echo $line. "<br>";
}
fclose($file);

// 文件写入
$file = fopen('export.csv', 'a');
$array = ['name' => 'Mike', 'age' => 45];

// 将键名写为 CSV 标题
fputcsv($file, array_keys($array[0]));

// 写入行 (格式为 csv)
foreach ($array as $row) {
    fputcsv($file, $row); 
}
fclose($file);

Errors

// 抛出错误
if (someCondition) {
    throw new Exception('Data format error');
}

// 捕获错误
try {
  $db->checkData($data);
} catch (Exception $e) {
    echo $e->getMessage();
}

OOP

// 类声明
class Person 
{
}

// 对象实例
$person = new Person

// 类属性和构造方法
class Person 
{
   protected $firstName;
   protected $lastName;
   public function __construct($firstName, $lastName) {
        $this->firstName = $firstName;
        $this->lastName = $lastName
   }

// 构造器属性提升(PHP 8)
class Person 
{
    public function __construct(protected $firstName, protected $lastName) 
    {

    }

// 获取和设置
class Person
{
    private $name;

    public function setName($name){
        if(!is_string($name)){
            throw new Exception('$name must be a string!');
        }
        $this->name = $name;
    }

    public function getName(){
        return $this->name;
    }
}

// 静态构造方法
public static function create(...$params) {
    return new self($params)
}
$person = Person::create(‘Mike’, ‘Taylor’);

//  静态方法
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}

// 调用静态方法
greeting::welcome();

// 静态方法调用
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }

  public function __construct() {
    static::welcome();
  }
}
new greeting();

// 静态常量
class Connection
{
  const MAX_USER = 100;
}
echo Connection::MAX_USER # 100

// 类继承
class Customer extends Person
{
    public function name()
    {
        parent::name();
        echo 'Override method';  
    }
}

// self 关键字引用当前类(不会像静态那样通过继承后期绑定修改)
self::welcome();

// 接口
interface Animal {
  public function makeSound();
}

class Cat implements Animal {
  public function makeSound() {
    echo "Meow";
  }
}
$animal = new Cat();
$animal->makeSound();

//Trait (mix-in)
trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

class Greetings {
    use HelloWorld;
}
$object = new Greetings();
$object->sayHello();

关注我!:Follow @EricTheCoder_

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://dev.to/ericchapman/my-beloved-ph...

译文地址:https://learnku.com/php/t/62217

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
讨论数量: 1

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!