概述
在面向对象编程中,PHP提供了一系列的魔术方法,这些魔术方法为编程提供了很多便利。PHP中的魔术方法通常以__(两个下划线)开始,并且不需要显示的调用而是由某种特定的条件出发。这篇文章简单总结了PHP中提供的魔术方法。
开始之前
在总结PHP的魔术方法之前先来定义两个类,以便后边示例使用:
 代码如下:
<?php
class Device {
    public $name;           
    public $battery;        
    public $data = array(); 
    public $connection;     
 
    protected function connect() {
        $this->connection = 'resource';
        echo $this->name . ' connected' . PHP_EOL;
    }
 
    protected function disconnect() {
        $this->connection = null;
        echo $this->name . ' disconnected' . PHP_EOL;
    }
}
 
class Battery {
    private $charge = 0;
 
    public function setCharge($charge) {
        $charge = (int)$charge;
        if($charge < 0) {
            $charge = 0;
        }
        elseif($charge > 100) {
            $charge = 100;
        }
        $this->charge = $charge;
    }
}
?>
Device类有四个成员属性和两个成员方法。Battery类有一个成员属性和一个成员方法。
构造函数和析构函数
构造函数和析构函数分别在对象创建和销毁时被调用。对象被“销毁”是指不存在任何对该对象的引用,比如引用该对象的变量被删除(unset)、重新赋值或脚本执行结束,都会调用析构函数。
__construct()
__construct()构造函数是目前为止最经常使用的函数。在创建对象时,可以在构造函数中做一些初始化工作。可以为构造函数定义任意多个参数,只要在实例化时传入对应个数的参数即可。构造函数中出现的任何异常都会阻止对象的创建。
 代码如下:
class Device {
   public function  __construct(Battery $battery, $name) {
       $this->battery = $battery;            
新闻热点
疑难解答