一,建立多個對象php
只需創造不一樣的對象ide
- class Nclass{
- public $name;
- public $type;
- function myfun(){
- return "演示如何建立多個對象":
- }
- }
建立三個對象函數
- $myclass1 = new Nclass();
- $myclass2 = new Nclass();
- $myclass3 = new Nclass();
- $myclass1->name="第一個名字".$myclass1->myfun();
- $myclass2->name="第二個名字".$myclass1->myfun();
- $myclass3->name="第三個名字".$myclass1->myfun();
二,$this關鍵字 用法,在當前對象中使用,表明當前對象,好比說,我叫phpmylove我能夠叫我phpmylove 也能夠稱呼我本身爲我,一個代詞。this
- <?
- class Nclass{
- public $name;
- public $type;
- function myfun(){
- return $this->name."演示如何使用this關鍵字 ";
- }
- function myfun2(){
- return $this->myfun()."這就是this的用法 ";
- }
- }
- $test = new Nclass();
- $test->name="本實例 ";
- echo $test->myfun2();
- ?>
本實例 演示如何使用this關鍵字 這就是this的用法spa
三,初始化對象 __construct 關鍵字對象
用戶初始化用途,等同於php4的同名方法。內存
- <?
- class Nclass{
- public $name;
- public $type;
- function __construct($name){
- $this->name=$name;
- }
- function myfun(){
- return $this->name."演示如何使用this關鍵字";
- }
- function myfun2(){
- return $this->myfun()."這就是this的用法";
- }
- }
- $test = new Nclass('本實例'); //上面__construct($name)中的$name能夠直接取到這裏的
- $test2 = new Nclass('2實例');
- echo $test->myfun2()."<br>";
- echo $test2->myfun2();
- ?>
輸出結果string
本實例演示如何使用this關鍵字這就是this的用法
2實例演示如何使用this關鍵字這就是this的用法it
四,析構函數 __destruct 垃圾回收機制,對象運行完畢時,釋放掉內存io
原則後進先出
- <?
- class Nclass{
- public $name;
- public $type;
- function __construct($name){
- $this->name=$name;
- }
- function myfun(){
- return $this->name."演示如何使用this關鍵字";
- }
- function myfun2(){
- return $this->myfun()."這就是this的用法";
- }
- function __destruct(){
- echo $this->name."已經被釋放了<br>";}
- }
- $test = new Nclass('本實例');
- $test2 = new Nclass('2實例');
- echo $test->myfun2()."<br>";
- echo $test2->myfun2()."<br>";
- ?>
輸出結果
本實例演示如何使用this關鍵字這就是this的用法
2實例演示如何使用this關鍵字這就是this的用法
2實例已經被釋放了
本實例已經被釋放了
若是不但願後進先出,只能在對象執行完畢時加入 $對象句柄 = null;
- <?
- class Nclass{
- public $name;
- public $type;
- function __construct($name){
- $this->name=$name;
- }
- function myfun(){
- return $this->name."演示如何使用this關鍵字";
- }
- function myfun2(){
- return $this->myfun()."這就是this的用法";
- }
- function __destruct(){
- echo $this->name."已經被釋放了<br>";}
- }
- $test = new Nclass('本實例');
- $test2 = new Nclass('2實例');
- echo $test->myfun2()."<br>";
- $test = null;
- echo $test2->myfun2()."<br>";
- ?>
輸出結果
本實例演示如何使用this關鍵字這就是this的用法 本實例已經被釋放了 2實例演示如何使用this關鍵字這就是this的用法 2實例已經被釋放了