2013-10-19 81 views
1

有人幫助我更輕鬆地理解魔術方法。瞭解PHP中的魔術方法

我知道魔法方法是在代碼的某個點觸發的,我不明白的是它們被觸發的點。 就像在__construct()的情況下一樣,它們在創建類的對象時觸發,並且要傳遞的參數是可選的。

請告訴我什麼時候__get(),__set(),__isset(),__unset()是特別觸發的。如果說到其他任何魔法方法,這將是很有幫助的。

+1

我想你會發現這個主題回答了一些你的問題: http://stackoverflow.com/questions/4713680/php-get-and-set-magic-methods – Marc

回答

0

以雙下劃線開頭的PHP函數 - 一個__ - 在PHP中被稱爲魔術函數(和/或方法)。它們是總是在類中定義的函數,並不是獨立的(在類之外)函數。在PHP中提供的神奇功能:

__construct(),__destruct(),__call(),__callStatic(),__get(),__set(),__isset(),__unset(),__sleep() __wakeup(),__toString(),__invoke(),__set_state(),__clone()和__autoload()。

現在,這裏是與__construct()的神奇功能的類的實例:

class Animal { 

public $height;  // height of animal 
public $weight;  // weight of animal 

public function __construct($height, $weight) 
{ 
$this->height = $height; //set the height instance variable 
$this->weight = $weight; //set the weight instance variable 

} 

} 
+1

這看起來像一個複製粘貼,請將來源歸功於信用。它不是你自己的答案。 –

2

PHP的魔術方法全部以「__」,只能是一個類內部使用。我試圖在下面寫出一個例子。

class Foo 
{ 
    private $privateVariable; 
    public $publicVariable; 

    public function __construct($private) 
    { 
     $this->privateVariable = $private; 
     $this->publicVariable = "I'm public!"; 
    } 

    // triggered when someone tries to access a private variable from the class 
    public function __get($variable) 
    { 
     // You can do whatever you want here, you can calculate stuff etc. 
     // Right now we're only accessing a private variable 
     echo "Accessing the private variable " . $variable . " of the Foo class."; 

     return $this->$variable; 
    } 

    // triggered when someone tries to change the value of a private variable 
    public function __set($variable, $value) 
    { 
     // If you're working with a database, you have this function execute SQL queries if you like 
     echo "Setting the private variable $variable of the Foo class."; 

     $this->$variable = $value; 
    } 

    // executed when isset() is called 
    public function __isset($variable) 
    { 
     echo "Checking if $variable is set..."; 

     return isset($this->$variable); 
    } 

    // executed when unset() is called 
    public function __unset($variable) 
    { 
     echo "Unsetting $variable..."; 

     unset($this->$variable); 
    } 
} 

$obj = new Foo("hello world"); 
echo $obj->privateVariable;  // hello world 
echo $obj->publicVariable;  // I'm public! 

$obj->privateVariable = "bar"; 
$obj->publicVariable = "hi world"; 

echo $obj->privateVariable;  // bar 
echo $obj->publicVariable;  // hi world! 

if (isset($obj->privateVariable)) 
{ 
    echo "Hi!"; 
} 

unset($obj->privateVariable); 

總之,使用這些魔術方法的主要優點之一是,如果你要訪問一個類(這是針對大量的編碼實踐)的私有變量,但它允許你指定的動作當某些事情被執行時;即設置變量,檢查變量等。

作爲說明,__get()__set()方法將只適用於私有變量。