PHP 8 中的属性
属性是一种类,可以用来向其他类、函数、类方法、类属性、常量和参数添加元数据。属性在运行时没有任何作用。
属性不会影响代码,但可用于反射API。PHP 8 中的属性允许其他代码检查类属性和方法。
我们可以为一个声明添加多个属性。
它可以解析类名。
属性可以命名空间。
它可以有零个或多个参数。
PHP 8 属性语法
在 PHP 8 中,#[ ] (# 和方括号)用于属性声明。
我们可以在 #[ ] 中声明多个属性,用逗号分隔。
参数是可选的,但需要用圆括号 () 括起来。
参数可以是字面值或常量表达式。
属性:语法
#[attribute]
例如,我们可以将属性用于类。
#[Attribute]
Final class EmpClass{
}示例:属性函数
#[Attr('param')]
function Exam(){}示例:属性类
#[Attr('param')]
class Exam{}示例:属性类属性
class Emp{
#[Attribute('param')]
public $name;
}示例:属性类常量
Class Emp{
#[Attribute('emp')]
private const EMP = 'emp';
}示例:属性函数
#[Attribute('emp')]
function exam(){}示例:属性方法参数
Function emp(#[Attribute('param')]$name){
}示例:使用函数、方法、参数和常量的 PHP 8 属性
<?php
#[MyAttribute]
class Emp
{
#[MyAttribute]
public const EMP = 'emp';
#[MyAttribute]
public $a;
#[MyAttribute]
public function foo(#[MyAttribute] $dept){}
}
$object = new #[MyAttribute] class(){};
#[MyAttribute]
function f() {}
$f1 = #[MyAttribute] function(){};
$f2 = #[MyAttribute] fn() => 1;
print_r($f1);
?>输出
Closure Object ( )
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP