所以我有这段代码:
<?php
class Product
{
public $name = 'default_name';
public $price = 0;
public $desc = 'default description';
function __construct($name, $price, $desc){
$this->name = $name;
$this->price = $price;
$this->desc = $desc;
}
public function getInfo(){
return "Product Name: " . $this->name;
}
}
$p = new Product();
$shirt = new Product("Space Juice T-Shirt", 20, "Awesome Grey T-Shirt");
$soda = new Product("Space Juice Soda", 2, "Grape Flavored Thirst Mutilator");
echo $shirt->getInfo();
?>
和PHP报告“缺少Product :: __ construct()的参数1”错误。我在一个领先的PHP课程中得到了这个例子,我很困惑,因为在这个简单的代码中似乎有一个错误。帮助会非常有用。
答案 0 :(得分:3)
在您的代码中,如果您要创建Product实例,则必须传递参数。而您已经拥有默认值。所以,确保安全:
<?php
class Product
{
public $name = 'default_name';
public $price = 0;
public $desc = 'default description';
function __construct($name = null, $price = null, $desc = null){
$this->name = $name ?: $this->name;
$this->price = $price ?: $this->price;
$this->desc = $desc ?: $this->desc;
}
public function getInfo(){
return "Product Name: " . $this->name;
}
}
$p = new Product();
$shirt = new Product("Space Juice T-Shirt", 20, "Awesome Grey T-Shirt");
$soda = new Product("Space Juice Soda", 2, "Grape Flavored Thirst Mutilator");
echo $shirt->getInfo();
?>
答案 1 :(得分:1)
您的构造不允许变量为空,因此
$p = new Product();
造成了这个问题。对于$ name,$ price和$ desc,它期待一些价值,即使它只是空字符串。
如果您将构造函数更改为:
function __construct($name = 'default_name', $price = 0, $desc = 'default description'){
$this->name = $name;
$this->price = $price;
$this->desc = $desc;
}
那么它不应再抛出那个错误了。