1、构造器属性提升 ~~~php <?php namespace myphp; class City{ public $name; public $city; // 构造方法 public function __construct($name, $city){ $this->name = $name; $this->city = $city; } public function fun(){ // 在类中使用伪变量: "$this" 引用当前类的成员变量 return '姓名:'.$this->name.',城市:'.$this->city.'<hr/>'; } } // 实例化 $obj = new City('张三','包头市'); echo $obj->fun(); ~~~ 更少的样板代码来定义并初始化属性 ~~~php <?php namespace myphp; class City{ // 构造方法 public function __construct(public $name,public $city){ } public function fun(){ // 在类中使用伪变量: "$this" 引用当前类的成员变量 return '姓名:'.$this->name.',城市:'.$this->city.'<hr/>'; } } // 实例化 $obj = new City('李四','包头市'); echo $obj->fun(); ~~~ 2、联合类型 类型 描述 bool 布尔型:true 和 false int 整型:负数 - 0 - 无限大 float 浮点型:带小数的数字(负数 - 0 - 无限大) string 字符串:汉字、英文、符号、其它国家语言 array 数组:一组数据的集合 object 对象:存储数据和有关如何处理数据的信息 mixed 新增:任何类型 ~~~php <?php namespace myphp; class City{ // 构造方法 public function __construct( public string $name, public string $city, public int|float $num ){ } public function fun(){ return '姓名:'.$this->name.',城市:'.$this->city.',今年是'.$this->num.'年<hr/>'; } } // 实例化 $obj = new City('李四','包头市',2022); echo $obj->fun(); ~~~ 3、mixed 类型 描述 mixed 新增:任何类型 ~~~php <?php namespace myphp; class City{ // 构造方法 public function __construct( public mixed $name, public mixed $city, public mixed $num ){ } public function fun(){ return '姓名:'.$this->name.',城市:'.$this->city.',今年是'.$this->num.'年<hr/>'; } } // 实例化 $obj = new City('李四','包头市',2022); echo $obj->fun(); ~~~