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}// 参数会传给 __construct10$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