標籤:物件導向 php 對象 function
Php物件導向學習筆記 – 構造、析構、對象賦值、複製
class student
{
public $stu_id; // 定義成員變數
public $stu_name;
public function sayName() // 成員函數
{
echo $this->stu_name; // $this 訪問該對象的成員變數
}
}
$stu = new Student; // 建立對象
$stu->stu_id = ‘0607001’;
$stu->stu_name = ‘小李’;
$stu->sayName();
注意:
class student
{
public $stu_id; // 定義成員變數
public $stu_name;
public function sayName() // 成員函數
{
var_dump($stu_name);
var_dump($GLOBALS[‘stu_name’]); // 兩種方法都無法訪問成員變數
//只要使用$this-> 才能訪問成員變數
}
}
$stu = new Student; // 建立對象
$stu->stu_id = ‘0607001’;
$stu->stu_name = ‘小李’;
$stu->sayName();
註:類中定義的屬性,不相當於類中定義的全域變數,不能直接再方法中使用屬性變數的形式訪問。
1. 構造和析構:
php的opp機制,在new完成時,會試著調用一個叫做__construct()的方法。
如果我們將初始化的代碼,寫到這個方法內,就可以完成自動初始化。
例子:
class Student
{
public $stu_id;
public $stu_name;
public function__construct($id,$name) // 構造
{
$this->stu_id= $id;
$this->stu_name= $name;
}
}
$stu = new Student(‘100511101’,’songyang’);
註:如果構造方法沒有參數,則 $stu = new Student 和 $stu = new Student() 都是對的。
構造方法的相容性問題:
php5,構造方法的名字,就是__construct().在php5之前,構造方法的名字為與類同名。為了相容,也同時支援與類同名的構造方法。
如果同時出現__construct() 和類名的構造方法:
例子:
class Student
{
public $stu_id;
public $stu_name;
public function __construct()
{
echo“construct run …”;
}
public function Student()
{
echo‘’Student run …”;
}
{
$stu = new Student;
輸出:construct run …
結論:如果同時出現兩種構造方法,調用__construct()
析構:
在對象被銷毀時,也會自動執行一個方法。
析構方法名字為:__destruct();
class Student
{
public $stu_id;
public $stu_name;
public function __construct()
{
echo“構造方法調用”;
}
//析構
publicfunction __destruct()
{
//釋放資源
echo“析構方法調用”;
}
}
該方法,用於釋放,該對象所佔用的額外資源,不是對象本身的記憶體空間!
什麼情況下,對象會被銷毀:
1. 指令碼周期結束,對象自動被銷毀。
2. 銷毀儲存該對象的變數。
$stu = new Student;
unset($stu);
輸出:析構方法調用
3. 儲存對象的變數,被賦值了其他資料。
$stu = new Student;
$stu = “new Value”; // 賦值其他資料時,Student對象被銷毀。
對象間的賦值
對象支援引用傳遞,不用&符號,因此不能通過=賦值的形式,得到一個新的對象。
例子
class Student
{
public $stu_id;
public $stu_name;
public function __construct($id,$name)
{
$this->stu_id= $id;
$this->stu_name= $name;
}
}
$stu1 = new Student(“100”,”song”);
$stu2 = $stu1;
echo $stu1->stu_name;
echo $stu2->stu_name;
$stu1->stu_name = “songyang”;
echo $stu1->stu_name;
echo $stu2->stu_name;
輸出:song song songyang songyang
複製
利用已有對象,得到相同的新對象。
需要使用關鍵字 clone
新對象 = clone 已有對象
例子:
class Student
{
public $stu_id;
public $stu_name;
public function __construct($id,$name)
{
$this->stu_id= $id;
$this->stu_name= $name;
}
}
$stu1 = new Student(“100”,”song”);
$stu2 = clone $stu1;
echo $stu1->stu_name;
echo $stu2->stu_name;
$stu1->stu_name = “songyang”;
echo $stu1->stu_name;
echo $stu2->stu_name;
輸出:song song songyang song
常見的操作,再複製對象時,需要對對象的某些特殊屬性進行修改。意味著,需要做一些特殊的處理。
使用,在複製時,自動調用的方法 __clone()來實現。
自動使用複製出來的對象,來調用這個__clone()方法,意味著,該方法內部的$this,表示新對象。
例子:
class Student
{
public $stu_id;
public $stu_name;
public function __construct($id,$name)
{
$this->stu_id= $id;
$this->stu_name= $name;
}
public function __clone()
{
$this->stu_id= “0607002”;
}
}
$stu1 = new Student(“1000”,”joker”);
$stu2 = clone $stu1;
echo $stu1->stu_id;
echo $stu2->stu_id;
輸出:1000 0607002