A dozen unpopular but easy-to-use PHP writing methods (the unpopular ones are shocking)

Environment: PHP8.1
1. else foreach/else for
//012
if(false) {
    
    

} else for($i = 0; $i < 3; $i++) {
    
    
    echo $i;
}

//012
if(false) {
    
    

} else foreach([0, 1, 2] as $v) {
    
    
    echo $v;
}
2. Anonymous function abbreviation
$func = function($val) {
    
    
    return $val;
};
//等同于
$func = fn($val) => $val;

$func(1);
3. Anonymous function overlay
$func = fn() => fn() => 1;
echo $func()();
4. The missing semicolon
//不会报错
<?php
echo 1
?>
5. Empty array combination operator
//使用??=,如果数组的元素有值且不为null,则赋值失败
$arr = [];
$arr['k1'] ??= 'v1';
print_r($arr);
$arr['k1'] ??= 'v2';
print_r($arr);
6. Use built-in classes to create empty objects
$obj = new stdClass();
$obj->i = 123;
echo $obj->i; //1
7. Use the ?-> safe navigation operator to avoid errors when calling non-existent methods or properties.
$obj = null;
var_dump($obj?->attr); //null
var_dump($obj?->method1()); //null
8. Call methods under a certain namespace individually
namespace Namespace1;
function func1() {
    
    
    echo 'func1';
}
function func2() {
    
    
    echo 'func2';
}

namespace Namespace2;
use function Namespace1\func1;
func1(); //1
func2(); //Fatal error: Uncaught Error: Call to undefined function Namespace2\func2() in t1.php:13 Stack trace: #0 {main} thrown in t1.php on line 13
9. Shift operator <</>>
//15的二进制是1111,向右移动两位,就是0011
echo 15 >> 2; //3
//15的二进制是1111,向左移动两位,就是111100
echo 15 << 2; //60
10. Bit operators |/&
//15的二进制是1111,2的二进制是0010
//逐个对比二进制位,都为1则为1,否则为0
echo 15 & 2; //0010->2
//逐个对比二进制位,有一个为1则为1,全部为0,则为0
echo 15 | 2;//1111->15
11. XOR operator ^
//异或运算符^,可以理解为二进制逐个对比二进制位,相同为0,不同为1
$a = 5; //0b0101
$b = 3; //0b0011
echo $a ^ $b; // 结果为 6(二进制表示为 0110)
12. Use the XOR assignment operator to exchange the values ​​of each other in two variables.
$a = 'a';
$b = 'b';
$a ^= $b;
$b ^= $a;
$a ^= $b;
echo $a, $b; //ba
13. Add snake head and execute PHP script using bash shell
touch test.php
chmod +x test.php
...
./test.php

Tells the operating system which interpreter to run when executing this script, using the PHP interpreter

#!/usr/bin/env php
<?php
echo 1;

Tell the operating system to use PHP in this directory when executing this script.

#!/usr/local/php/bin/php
<?php
echo 1;

Guess you like

Origin blog.csdn.net/weixin_42100387/article/details/135002909