[英]How do I declare a variable of an extended class in php
I am trying to declare a variable, specifically the $publisher variable , but it is not working. 我正在尝试声明一个变量,特别是$ publisher变量 ,但是它不起作用。 I am unsure if I have extended the class correctly. 我不确定我是否正确扩展了课程。
Books is the main class and Novel is the extended class. 书籍是主要课程, 小说是延伸课程。
THE PHP CLASSES 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;
}
}
** CALLING THE CLASS ** **上课**
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();
** THE RESULT ** ** 结果 **
Physics for High School
Advanced Chemistry
Algebra
2000
1200
3400
yes
As you can see it does not declare the $Publisher() Value. 如您所见,它没有声明$ Publisher()值。
My question is What am I missing? 我的问题是我想念什么?
If you enable error reporting you will see the error, the code is not actually being run. 如果启用错误报告,您将看到错误,该代码实际上并未在运行。
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Books::__construct(), 0 passed in ... on line 62 and exactly 2 expected 致命错误:未被捕获的ArgumentCountError:函数Books :: __ construct()的参数太少,在第62行传递了0,正好是2
Because you are extending the class and the parent has a construct, you need to either pass it the values $pN = new Novel('To Kill a Mockingbird', 2.99);
因为您正在扩展类并且父级具有构造,所以您需要向其传递值$pN = new Novel('To Kill a Mockingbird', 2.99);
, or define them a default. ,或为它们定义一个默认值。
public function __construct($par1 = '',$par2 = ''){
$this->title = $par1;
$this->price = $par2;
}
Then it will work fine: 然后它将正常工作:
Physics for High School 高中物理
Advanced Chemistry 先进化学
Algebra 代数
2000 2000
1200 1200
3400 3400
yesBarnes and Noble 是巴恩斯和诺布尔
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.