[英]Importing Parent function data in child php oop
我試圖通過在子級中調用父函數數據來學習php oop的簡單方法。 但是我在某個地方犯了錯誤。
class name{
var $firstname;
var $lastname;
var $name;
public function name($firstname, $lastname){
$this->firstname=$firstname;
$this->lastname=$lastname;
$this->name=$this->firstname." ".$this->lastname;
return $this->name;
}
}
class sentence extends name{
var $name;
var $letter;
function sentence(){
$this->letter="My name is ";
echo $this->letter.$this->name;
}
}
$name=new name(ABC, Xyz);
$letter=new sentence();
我創建了一個調用來獲取名稱輸入,並創建了另一個子類來編寫句子。 但是不能在孩子中叫名字。
快速修復,因為那可能就是您想要的。
<?php
class name {
private $firstname;
private $lastname;
private $name;
private $sentence;
public function __construct($firstname, $lastname){
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->name = $firstname . " " . $lastname;
$this->sentence = "My name is : " . $this->name;
}
public function getName(){
return $this->name;
}
public function getSentence(){
return $this->sentence;
}
}
$instance = new name("test","lastname");
echo $instance->getSentence();
?>
class name
{
public $firstname;
public $lastname;
public $name;
public function name($firstname, $lastname)
{
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->name = $this->firstname.' '.$this->lastname;
return $this->name;
}
}
class sentence extends name
{
public $name;
public $letter;
public function greeting()
{
$this->letter = 'My name is ';
echo $this->letter.$this->name;
}
}
//$name=new name(ABC, Xyz);
$letter = new sentence('ABC', 'Xyz');
$letter->greeting();
感謝@ManhNguyen
您是否要讀取父類中變量的狀態?
這不是OOP的工作方式。
您必須將所有變量組合到一個類中,或者將其作為參數傳遞給想要訪問數據的函數。
第二,您似乎並沒有使用__construct
函數,而是將變量傳遞到也是NO-NO的new name()
函數中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.