这里有一个简单的父母和子女课程,任何人都可以向我解释为什么这不能回应total_pages?我已经传递了价值和一切......
另一件事(无关的问题),当我已经在父母的构造函数中传递参数时,需要将参数传递给子节点吗?没有继承意味着所有的值都将来自父...?
三江源。
class Book{
protected $total_pages;
protected $page_type;
function set_data($total_pages, $page_type){
$this->total_pages = $total_pages;
$this->page_type = $page_type;
}
}
class Final_look extends Book{
function preview_book(){
echo $this->total_pages;
}
}
$Book = new Book;
$Book->set_data(110, "thick");
$Final_look = new Final_look;
$Final_look->preview_book();
答案 0 :(得分:3)
您创建了2个不同的对象!这两个对象无关,它们完全相互独立!
我认为你想要的是这样的:
<?php
class Book{
protected $total_pages;
protected $page_type;
function set_data($total_pages, $page_type){
$this->total_pages = $total_pages;
$this->page_type = $page_type;
}
}
class Final_look extends Book{
function preview_book(){
echo $this->total_pages;
}
}
$Book = new Final_look;
//^^^^^^^^^^ create Object from 'Final_look' so you can use all functions
$Book->set_data(110, "thick");
$Book->preview_book();
//^^^^^^^^^^^^ Same object which calls this function
?>
输出:
110