如何在 php 中声明扩展 class 的变量

How do I declare a variable of an extended class in php

我正在尝试声明一个变量,特别是 $publisher 变量,但它不起作用。我不确定我是否正确扩展了 class。

书籍是主要class和小说是扩展class.

PHPCLASSES

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;
    }

}

** 调用 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();

** 结果 **

Physics for High School
Advanced Chemistry
Algebra
2000
1200
3400
yes

如您所见,它没有声明 $Publisher() 值。

我的问题是我错过了什么?

如果启用错误报告,您将看到错误,代码实际上不是 运行。

Fatal error: Uncaught ArgumentCountError: Too few arguments to function Books::__construct(), 0 passed in ... on line 62 and exactly 2 expected

因为您正在扩展 class 并且父级有一个构造,您需要将值 $pN = new Novel('To Kill a Mockingbird', 2.99); 传递给它,或者将它们定义为默认值。

public function __construct($par1 = '',$par2 = ''){
    $this->title = $par1;
    $this->price = $par2;
}

然后就可以正常工作了:

高中物理
高等化学
代数
2000
1200
3400
yesBarnes and Noble

https://3v4l.org/Ydthj