php中的魔術方法

來源:互聯網
上載者:User

標籤:php   魔術方法   

PHP魔術方法:

__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() 和 __debugInfo() 等方法在 PHP 中被稱為"魔術方法"(Magic methods)。在命名自己的類方法時不能使用這些方法名,除非是想使用其魔術功能。


__construct(),類的建構函式__destruct(),類的解構函式__call(),在對象中調用一個不可存取方法(私人或者不存在)時調用__callStatic(),用靜態方式中調用一個不可存取方法時調用__get(),獲得一個類的成員變數時調用__set(),設定一個類的成員變數時調用__isset(),當對不可訪問屬性調用isset()或empty()時調用__unset(),當對不可訪問屬性調用unset()時被調用。__sleep(),執行serialize()時,先會調用這個函數__wakeup(),執行unserialize()時,先會調用這個函數__toString(),類被當成字串時的回應方法__invoke(),調用函數的方式調用一個對象時的回應方法__set_state(),調用var_export()匯出類時,此靜態方法會被調用。__clone(),當對象複製完成時調用

__construct()和__destruct()
建構函式__construct()在對象被建立的時候調用,解構函式__destruct()在對象消亡的時候被調用

<?php  class ConDes{    protected $a = '';    function __construct(){        echo '在建構函式中<br>';    }    function __destruct(){        echo '在解構函式中<br>';    }}$val = new ConDes();unset($val);?><pre name="code" class="php">

輸出:
 

在建構函式中在解構函式中

__call()和__callStatic()在對象中調用一個不可存取方法時會調用這兩個方法,後者為靜態方法。

<?php  class MethodTest  {    public function __call ($name, $arguments) {    var_dump($arguments);        echo "object method $name and ".implode(',',$arguments)."<br>";    }    public static function __callStatic ($name, $arguments) {        echo "static method $name and ".implode(',',$arguments)."<br>";    }}$obj = new MethodTest;$obj->runTest('in object context','another arg');MethodTest::runTest('in static context');  ?>
輸出:

array (size=2)
  0 => string ‘in object context‘ (length=17)
  1 => string ‘another arg‘ (length=11)

object method runTest and in object context,another arg
static method runTest and in static context


__get(),__set(),__isset()和__unset()

當擷取一個不可訪問的類成員變數或設定一個不可訪問的類成員變數時調用這兩個函數。

<?phpclass MethodTest  {    private $data = array();    private $a = '';    public $bbb = '';    public function __set($name, $value){        $this->data[$name] = $value;echo '__set';var_dump($this->data);    }    public function __get($name){echo '__get';var_dump($this->data);        if(array_key_exists($name, $this->data))            return $this->data[$name];        return NULL;    }    public function __isset($name){echo '__isset';        return isset($this->data[$name]);    }    public function __unset($name){echo '__unset';        unset($this->data[$name]);    }}$in = new MethodTest();$in->a = 'aaaa';$aaa = $in->a;$res = isset($in->c)? 'set':'not set';echo '<br>'.$res.'<br>';unset($in->a);?>
輸出:

__set
array (size=1)
  ‘a‘ => string ‘aaaa‘ (length=4)
__get
array (size=1)
  ‘a‘ => string ‘aaaa‘ (length=4)
__isset
not set
__unset


__sleep()和__wakeup()

當我們在執行serialize()和unserialize()時,會先調用這兩個函數。例如我們在序列化一個對象時,這個對象有一個資料庫連結,想要在還原序列化中恢複連結狀態,則可以通過重構這兩個函數來實現連結的恢複。

<?phpclass Connection {    public $link;    private $server, $username, $password, $db;        public function __construct($server, $username, $password, $db)    {        $this->server = $server;        $this->username = $username;        $this->password = $password;        $this->db = $db;        $this->connect();    }        private function connect()    {        $this->link = mysql_connect($this->server, $this->username, $this->password);        mysql_select_db($this->db, $this->link);    }        public function __sleep()    {    echo 'sleep<br>';        return array('server', 'username', 'password', 'db');    }        public function __wakeup()    {    echo 'wakeup<br>';        $this->connect();    }}$a = new Connection('localhost','mosi','moshi','test');$sql = 'select id,username from user limit 1';$res = mysql_query($sql,$a->link);$res = mysql_fetch_array($res);var_dump($res);$sres = serialize($a);mysql_close($a->link);//unset($a);$unsres = unserialize($sres);var_dump($unsres);$sql = 'select id,username from user limit 1';$ress = mysql_query($sql,$unsres->link);$ress = mysql_fetch_array($ress);var_dump($ress);?>
輸出:

array (size=4)
  0 => string ‘1‘ (length=1)
  ‘id‘ => string ‘1‘ (length=1)
  1 => string ‘m0sh1‘ (length=5)
  ‘username‘ => string ‘m0sh1‘ (length=5)
sleep
wakeup
object(Connection)[2]
  public ‘link‘ => resource(6, mysql link)
  private ‘server‘ => string ‘localhost‘ (length=9)
  private ‘username‘ => string ‘moshi‘ (length=4)
  private ‘password‘ => string ‘moshi‘ (length=5)
  private ‘db‘ => string ‘test‘ (length=4)
array (size=4)
  0 => string ‘1‘ (length=1)
  ‘id‘ => string ‘1‘ (length=1)
  1 => string ‘m0sh1‘ (length=5)
  ‘username‘ => string ‘m0sh1‘ (length=5)


__toString()

對象當成字串時的回應方法。例如使用echo $obj;

<?php  class TestClass  {    public function __toString() {        return 'this is a object';    }}$class = new TestClass();echo $class;  ?>
輸出:

this is a object

這個方法只能返回字串,而且不可以在這個方法中拋出異常,否則會出現致命錯誤。


__invoke()

調用函數的方式調用一個對象時的回應方法。

<?phpclass Invoke{public function __invoke(){echo 'in invoke<br>';}}class noInvoke{}$obj = new Invoke();$obj();var_dump(is_callable($obj));$obj2 = new noInvoke();//$obj2();var_dump(is_callable($obj2));

輸出:

in invoke
boolean true
boolean false


__set_state()

調用var_export()匯出類時,此靜態方法會被調用。

<?php  class A  {    public $var1;    public $var2;public static function __set_state ($arr) {        $obj = new A;        $obj->var1 = 'var11';        $obj->var2 = $arr['var2'];        return $obj;    }}$a = new A;$a->var1 = 5;$a->var2 = 'foo';var_dump($a);  var_export($a);  eval('$ress = '.var_export($a,true).';');var_dump($ress);?>

輸出:

object(A)[1]
  public ‘var1‘ => int 5
  public ‘var2‘ => string ‘foo‘ (length=3)
A::__set_state(array( ‘var1‘ => 5, ‘var2‘ => ‘foo‘, ))
object(A)[2]
  public ‘var1‘ => string ‘var11‘ (length=5)
  public ‘var2‘ => string ‘foo‘ (length=3)


__clone()

當對象複製完成時調用。

<?php  class Singleton {      private static $_instance = NULL;    // 私人構造方法     private function __construct() {}    public static function getInstance() {        if (is_null(self::$_instance)) {            self::$_instance = new Singleton();        }        return self::$_instance;    }    // 防止複製執行個體    public function __clone(){        die('Clone is not allowed error: ' . E_USER_ERROR);    }}$a = Singleton::getInstance();$b = Singleton::getInstance();if( $a === $b ){echo 'equal<br>';}$c = clone $b;?>

輸出:

equal
Clone is not allowed error: 256


PHP 魔術常量:簡介在這裡

php中的魔術方法

聯繫我們

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