我试图声明一个变量,特别是$ publisher变量,但它不起作用.我不确定我是否正确地扩展了课程.
书籍是主要的类,而Novel是扩展类.
PHP课程
class Books {
/* Member variables */
public $price;
public $title;
/* Member functions */
public function setPrice($par){
$this->price = $par;
}
public function getPrice(){
echo $this->price.'<br/>';
}
public function setTitle($par){
$this->title = $par;
}
public function getTitle(){
echo $this->title.'<br/>';
}
public function __construct($par1,$par2){
$this->title = $par1;
$this->price = $par2;
}
}
class Novel extends Books {
public $publisher;
public function setPublisher($par){
$this->publisher = $par;
}
public function getPublisher(){
echo $this->publisher;
}
}
Run Code Online (Sandbox Code Playgroud)
**打电话给**
include 'includes/book.inc.php';
$physics = new Books("Physics for High School" , 2000);
$chemistry = new Books("Advanced Chemistry" , 1200);
$maths = new Books("Algebra", 3400);
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
if (class_exists('Novel')) {
echo 'yes';
}
$pN = new Novel();
$pN->setPublisher("Barnes and Noble");
$pN->getPublisher();
Run Code Online (Sandbox Code Playgroud)
**结果**
Physics for High School
Advanced Chemistry
Algebra
2000
1200
3400
yes
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它没有声明$ Publisher()值.
我的问题是我错过了什么?
如果启用错误报告,您将看到错误,代码实际上并未运行.
致命错误:未捕获的ArgumentCountError:函数Books :: __ construct()的参数太少,0在第62行传入......正好是2个预期的
因为您正在扩展类并且父类具有构造,所以您需要将值传递给它$pN = new Novel('To Kill a Mockingbird', 2.99);,或者将它们定义为默认值.
public function __construct($par1 = '',$par2 = ''){
$this->title = $par1;
$this->price = $par2;
}
Run Code Online (Sandbox Code Playgroud)
然后它会正常工作:
高中物理
高等化学
代数
2000
1200
3400
yesBarnes and Noble