[英]How to pass public value from parent class to child class in PHP?
[英]Why is my PHP child class not getting public and protected vars from the parent?
我正在大腦凍結,我懷疑這個真的很簡單。 考慮這段代碼,有兩個類:
<?php
class myparentclass {
protected $vara;
private $varb;
public $varc;
public $_childclass;
function __construct() {
$this->vara = "foo";
$this->varb = "bar";
$this->varc = ":(";
$this->_childclass = new mychildclass;
}
}
class mychildclass extends myparentclass {
function __construct() {
print_r ($this);
}
}
print "<pre>";
$foo = new myparentclass();
output 是:
mychildclass Object
(
[vara:protected] =>
[varb:private] =>
[varc] =>
[_childclass] =>
)
我知道不應該設置 $varb,但是其他的呢?
如果您在子 class 中定義了一個新的__construct()
,就像您已經完成打印 vars 一樣,您還需要顯式調用父的構造函數。 如果您沒有在子 class 中定義任何__construct()
,它將直接繼承父的並且所有這些屬性都將被設置。
class mychildclass extends myparentclass {
function __construct() {
// The parent constructor
parent::__construct();
print_r ($this);
}
}
您必須在子 class 構造函數中調用父 class 構造函數。
function __construct() {
parent::__construct();
print_r ($this);
}
如果在子 class 中重新定義構造函數,則必須調用父構造函數。
class mychildclass extends myparentclass {
function __construct() {
parent::__construct();
print_r ($this);
}
}
應該工作正常。
如果子 class 有自己的構造函數,則必須從其中顯式調用父構造函數(如果要調用它):
parent::__construct();
你的父構造函數永遠不會被孩子執行。 像這樣修改 mychildclass:
function __construct() {
parent::__construct();
print_r ($this);
}
您正在使用父 class 中的構造函數覆蓋父類的構造函數。 您可以使用 parent::__construct(); 從您的孩子 class 調用父母的構造函數;
然而,myparentclass 的構造函數的最后一行調用了 mychildclass 的構造函數,而 mychildclass 的構造函數又調用了父構造函數,等等。 你的意思是實現這一目標嗎?
<?php
class myparentclass {
protected $vara;
private $varb;
public $varc;
function __construct() {
$this->vara = "foo";
$this->varb = "bar";
$this->varc = ":(";
}
}
class mychildclass extends myparentclass {
function __construct() {
parent::__construct();
print_r ($this);
}
}
print "<pre>";
$foo = new mychildclass();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.