php 物件導向詳解_構造方法與析構方法

來源:互聯網
上載者:User

第七章(4)物件導向詳解_構造方法與析構方法
特殊的引用$this的使用
執行個體說明:
class Ren
{
 var $xingming;
 var $nianling;
 var $xingbie;
 function shuohua()
 {echo "我的姓名是:".$this->xingming.",我的年齡是:".$this->nianling.",我的性別是:".$this->xingbie."<br>";}
 function zoulu()
 {echo "我在走路<br>";}
 function chifan()
 {echo "我在吃飯<br>";}
}
$r1=new Ren();    $r2=new Ren();    $r3=new Ren();
$r1->xingming="張三";    $r2->xingming="李四";    $r3->xingming="王五";
$r1->nianling=90;    $r2->nianling=23;    $r3->nianling=41;
$r1->xingbie="男";    $r2->xingbie="女";    $r3->xingbie="男";
//人1.2.3各自說出自己的姓名.年齡.性別:
$r1->shuohua();    $r2->shuohua();    $r3->shuohua();
輸出結果:
我的姓名是:張三,我的年齡是:90,我的性別是:男
我的姓名是:李四,我的年齡是:23,我的性別是:女
我的姓名是:王五,我的年齡是:41,我的性別是:男
$this的作用:代表對象的一個屬性,相當於第一人稱"我"的概念.
構造方法的特點:名稱與類相同,對象一產生的時候自動調用,去初始化成員屬性.
執行個體說明:(此執行個體是在php4裡面的聲明方法)
class Ren
{
 var $xingming;
 var $nianling;
 var $xingbie;
 function Ren($xingming,$nianling,$xingbie)
 {
  $this->xingming=$xingming;
  $this->nianling=$nianling;
  $this->xingbie=$xingbie;
 }
 function shuohua()
 {echo "我的姓名是:".$this->xingming.",我的年齡是:".$this->nianling.",我的性別是:".$this->xingbie."<br>";}
 function zoulu()
 {echo "我在走路<br>";}
 function chifan()
 {echo "我在吃飯<br>";}
}
$r1=new Ren("張三",90,"男");
$r2=new Ren("李四",23,"女");
$r3=new Ren("王五",41,"男");
$r1->shuohua();    $r2->shuohua();    $r3->shuohua();
此例如上例輸出結果完全相同.
在php5版本中的構造方法是function__construct(),不用寫類名,作用相同.
析構方法__destruct()在程式結束前釋放要釋放的東西的方法.
執行個體說明:
class Ren
{
 var $xingming;
 var $nianling;
 var $xingbie;
 function __construct($xingming,$nianling,$xingbie)
 {
  $this->xingming=$xingming;
  $this->nianling=$nianling;
  $this->xingbie=$xingbie;
 }
 function shuohua()
 {echo "我的姓名是:".$this->xingming.",我的年齡是:".$this->nianling.",我的性別是:".$this->xingbie."<br>";}
 function zoulu()
 {echo "我在走路<br>";}
 function chifan()
 {echo "我在吃飯<br>";}
 function __destruct()
 {echo $this->xingming."再見<br>";}
}
$r1=new Ren("張三",90,"男");
$r2=new Ren("李四",23,"女");
$r3=new Ren("王五",41,"男");
$r1->shuohua();    $r2->shuohua();    $r3->shuohua();
輸出結果:
我的姓名是:張三,我的年齡是:90,我的性別是:男
我的姓名是:李四,我的年齡是:23,我的性別是:女
我的姓名是:王五,我的年齡是:41,我的性別是:男
王五再見    李四再見    張三再見

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.