我現在自己編寫了一個兩個繼承關係的類,父類執行個體化後子類不知道怎麼調用父類已經執行個體後儲存的變數
先把代碼粘在下面:
Class Identification{//Identification函數將name與code聯絡起來public function Identification(){//串連到InfoModel$DB_Info = M('Info');$condition->Name = $this->name;return $this->code = $DB_Info->where($condition)->getfield('Code');}public $name;protected $code;}Class PT_Info extends Identification{public function get_BloodTest(){$DB_BloodTest = M('Bloodtest');$condition->Code = $this->code;echo "This is Code:".$this->code;$this->Info_BT_WBC = $DB_BloodTest->where($condition)->getfield('WBC');echo "This is WBC:".$this->Info_BT_WBC;$this->Info_BT_NEPer = $DB_BloodTest->where($condition)->getfield('NEPer');echo "This is NE%:".$this->Info_BT_NEPer;$this->Info_BT_LYPer = $DB_BloodTest->where($condition)->getfield('LY%');echo "This is LY%:".$this->Info_BT_LYPer;$this->Info_BT_MOPer = $DB_BloodTest->where($condition)->getfield('MO%');echo "This is MO%:".$this->Info_BT_MOPer;}public $Info_BT_WBC;public $Info_BT_NEPer;public $Info_BT_LYPer;public $Info_BT_MOPer;}public function tclass(){$neal = new Identification();$neal->name = 'Neal';$code = $neal->Identification();$this->assign('name',$neal->name);$this->assign('code',$code);$neal_BT = new PT_Info();$neal_BT->get_BloodTest();$this->assign('Info_BT_WBC',$neal_BT->Info_BT_WBC);$this->assign('Info_BT_NEPer',$neal_BT->Info_BT_NEPer);$this->assign('Info_BT_LYPer',$neal_BT->Info_BT_LYPer);$this->assign('Info_BT_MOPer',$neal_BT->Info_BT_MOPer);$this->display();}
如上面代碼:我把Identification類執行個體化為neal後儲存了一個變數$code,之後執行個體化其子類PT_Info為neal_BT,此時需要調用已經儲存在neal中的$code變數值(詳見PT_Info類裡的函數用法)
我不想在PT_Info類裡面再單獨存一個$code變數,想借用繼承關係,畢竟往後還有很多類似的結構,那樣寫的話整體會很亂
話句話說我先在執行個體化的子類要調用一個執行個體化的父類裡的變數,這兩個類在定義是有繼承關係,可是執行個體化後我不知道怎麼告訴編譯器這兩個類(neal和neal_BT)之間存在繼承關係
註:我整個項目使用ThinkPHP架構寫的,所以有的函數(比如‘M’方法)並非PHP預設的寫法
跪求大神幫忙解答!!!
回複討論(解決方案)
你的概念出問題了
Class PT_Info extends Identification 後
PT_Info 和 Identification 就是兩個獨立的類了,雖然 PT_Info 繼承了 Identification 一些東西
這就和 你 不是 你父親 是一個道理
Class Identification
{
public function Identification()
你在 Identification 定義了 Identification 方法,這就是建構函式了(據說 php7 取消了這個 C++ 來的特徵)
那麼,你在執行個體化 PT_Info 時,這個 Identification 方法就會自動被執行 code 屬性就已經有值了
注意:建構函式是沒有傳回值的(寫了也沒用)
因此 tclass 方法中的 $neal = new Identification(); 是沒有意義的
後面還有 $neal_BT = new PT_Info();
就是說 $DB_Info->where($condition)->getfield('Code'); 被執行了兩次,多了一次無用功
你的概念出問題了
Class PT_Info extends Identification 後
PT_Info 和 Identification 就是兩個獨立的類了,雖然 PT_Info 繼承了 Identification 一些東西
這就和 你 不是 你父親 是一個道理
Class Identification
{
public function Identification()
你在 Identification 定義了 Identification 方法,這就是建構函式了(據說 php7 取消了這個 C++ 來的特徵)
那麼,你在執行個體化 PT_Info 時,這個 Identification 方法就會自動被執行 code 屬性就已經有值了
注意:建構函式是沒有傳回值的(寫了也沒用)
因此 tclass 方法中的 $neal = new Identification(); 是沒有意義的
後面還有 $neal_BT = new PT_Info();
就是說 $DB_Info->where($condition)->getfield('Code'); 被執行了兩次,多了一次無用功
太感謝啦!!的確是我自己理解上的問題,您這個解釋太及時了多謝多謝!!!