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

时间:2018-07-25 23:08:08

标签: php oop extends

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

图书是主要课程,小说是扩展课程。

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

}

**召唤课堂**

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()值。

我的问题是我想念什么?

1 个答案:

答案 0 :(得分:5)

如果启用错误报告功能,则会看到错误消息,表明该代码实际上并未在运行。

  

致命错误:未捕获的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;
}

然后它将正常工作:

高中物理
高级化学
代数
2000
1200
3400
是巴恩斯和诺布尔

https://3v4l.org/Ydthj