class中$this->construct($x); 意思

來源:互聯網
上載者:User
class aaa{
var $b;
function __construct($x){
$this->b= $x;
}
function b($x) {
$this->__construct($x);
}
function c{...}
function d(){...}
}

$k= new aaa(x);
$html_text = $k->d();

上面類裡 的
function b($x) {
$this->__construct($x);
}
是怎麼意思可以省略嗎?誰能具體解釋一下?


回複討論(解決方案)

__construct 是建構函式
在 new classname 時被自動執行,主要的功能就是像你執行個體的那樣做些初始化的工作
如果你沒有什麼事情要他做,自然就可以省略

function b($x) {
$this->__construct($x);
}


改成

function b($x) {
$this->b=$x;
}
你就明白了吧

__construct 建構函式
當類被執行個體化時自動調用. 通常用來初始化工作.

更正一下
class裡面的function b($x) { $this->__construct($x); }這句原代碼是這樣的
function aaa($x) { $this->__construct($x); }//更正一下 該函數名和class aaa名字相同 //只是這句不太理解,

我的理解是
在用$k= new aaa("x"); 執行個體化的時候會執行function __construct($x){$this->b= $x;} 從而完成賦值;
但class裡面的其他的function c{...}和function d(){...}不會被執行,


那麼問題是:
class裡面的 唯一一個和class名稱一樣的function aaa且裡面僅有一句話 $this->__construct($x); 起什麼作用?
如果是在這個時候$k= new aaa("x");執行個體化就被執行了嗎?
試了下好象沒有被執行,因為我在裡面加上echo "x"改成function aaa($x) { $this->__construct($x);echo "aaaaa"; echo $x;}
$k= new aaa("x");後不會有輸出;依然要在執行個體化後用$k->aaa(55555)才能輸出
所以不明白和class裡面同名稱僅有 $this->__construct("執行個體化時的參數一樣的參數")的vunction和什麼特殊的作用?

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.