有趣的PHP语法和特性
- 2024-10-22 20:20:00
 - 丁国栋
 - 原创 299
 
PHP发展到现在,在自身发展逐渐完美的同时,也一直在吸取其他编程语言的的优点,于是一个个吸引人的特性被发布出来。
1、只读属性:只能在初始化时赋值,之后不可修改。
class User
  {
    public readonly string $username;
    public function __construct(string $username)
      {
          $this->username = $username;
      }
  }
2、枚举:一组命名的常量,用于表示特定状态或分类。https://www.php.net/manual/en/language.enumerations.basics.php
<?php
    enum Suit
    {
        case Hearts;
        case Diamonds;
        case Clubs;
        case Spades;
    }
    function pick_a_card(Suit $suit)
    {
        /* ... */
    }
$val = Suit::Diamonds;
// OK
    pick_a_card($val);
// OK
    pick_a_card(Suit::Clubs);
// TypeError: pick_a_card(): Argument #1 ($suit) must be of type Suit, string given
    pick_a_card('Spades');
  3、匹配表达式:switch 语句的现代替代方案,更灵活。
$status = 'active';
$message = match ($status) {
'active' => '用户处于活跃状态',
'inactive' => '用户处于非活跃状态',
'pending' => '用户处于待定状态',
default => '状态未知',
};
4、构建器属性提升:直接在构建器中设置属性值。
class Point {
public function __construct(public float $x,
public float $y
) {}
}
$point = new Point(1.5, 2.5);
5、命名参数:通过参数名传递值,不再受位置限制。
function createUser(string $username, bool $isAdmin = false) {
// 您的代码在此}
createUser(username: 'john_doe', isAdmin: true);
6、Nullsafe 运算符:简化空值检查。
$user = getUser();
$profile = $user?->getProfile()?->getBio();7、联合类型:允许变量同时接受多种类型的值。
function processNumber(int|float $number): int|float {
return $number * 2;}
8、字符串键解包:简化数组合并操作。
$array1 = ['a' => 1, 'b' => 2];
$array2 = ['c' => 3, ...$array1];print_r($array2);
// 输出: ['c' => 3, 'a' => 1, 'b' => 2]
9、JSON_THROW_ON_ERROR:自动抛出 JSON 错误异常。
ini_set('json.exceptions', '1');
try {
$data = json_decode('{"invalidJson":}', true);
} catch (JsonException $e) {
echo 'JSON 错误: ' . $e->getMessage();
}
10、JIT 编译:实时编译 PHP 代码,提高脚本运行速度。它与 opcache 扩展捆绑,可在 php.ini 中启用。
zend_extension=php_opcache.dll
opcache.jit=1205 ; configuration using four digits OTRCopcache.enable_cli=1 ; in order to work in the CLI as well
opcache.jit_buffer_size=128M ; dedicated memory for compiled code
 
    
      评论列表
    
    
            匿名
             2024-10-30 14:06:22
             Email: ****@****             IP: 123.*.*.86 (山东/青岛)
            回复
          
          PHP中存在一些潜在的陷阱。例如,当使用 unset 删除一个对象的属性时,如果该属性原本并不存在,PHP会自动为该对象添加一个空的属性。这意味着,当你执行 unset($object->$property->$something) 时,如果 $object 中没有 $property 属性,PHP 会创建一个空的 $property 属性
                  1/1 
          
                           
          
                           
    
                     发表评论