PHP 的 构造函数

等级 4239 次按键

使用构造函数初始化商品的名称和价格,然后输出“Laptop: $999.99”。

PHP 代码

1class Product {
// 存放商品名称和价格的类型化属性
2 public string $name;
3 public float $price;
4
// __construct 在用 new 创建对象时自动调用
5 public function __construct(string $name, float $price) {
// $this 是新建的对象;把参数保存到属性中
6 $this->name = $name;
7 $this->price = $price;
8 }
9}
// 参数会传给 __construct
10$item = new Product("Laptop", 999.99);
// \$ 输出字面的美元符号,结果为“Laptop: $999.99”
11echo "$item->name: \$$item->price";

运行结果

Laptop: $999.99
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 PHP 代码中需要输入的符号及其出现次数。

  • $× 12
  • ;× 6
  • -× 4
  • "× 4
  • >× 4
  • =× 3
  • _× 2
  • ,× 2
  • (× 2
  • )× 2

PHP 等级 4 的更多代码示例

← 返回 PHP 打字练习