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