dongweihuan8610 2018-07-25 23:08
浏览 92
已采纳

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

I am trying to declare a variable, specifically the $publisher variable, but it is not working. I am unsure if I have extended the class correctly.

Books is the main class and Novel is the extended class.

THE PHP CLASSES

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.

My question is What am I missing?

  • 写回答

1条回答 默认 最新

  • doufan3958 2018-07-25 23:16
    关注

    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

    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);, 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
    1200
    3400
    yesBarnes and Noble

    https://3v4l.org/Ydthj

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码