PHP中什么是魔术方法

PHP魔术方法以双重下划线字符开头,它们是:

  • __construct()
  • __destruct()
  • __call()
  • __sleep()
  • __callstack()
  • __get()
  • __set()
  • __unset()
  • __walkup()
  • __tostring()
  • __invoke()
  • __setstate()
  • __clone()

为什么他们被称为"魔术"方法
它的定义由程序员提供,换句话说是。
PHP不提供这些方法的定义。
程序员写入定义实际这些方法的代码。
用户无法调用这些方法,这就是为什么它被称为"魔法"方法,因为PHP将调用场景后面的功能,并且这些方法始终在类中定义。

例如:

php中的_sleep和_wakeup方法

_sleep()
当我们的程序中有一个很大的对象并且我们不想完全保存这个对象时,它是很有用的。它还用于提交和执行简单的清理任务。

_wakeup()
当我们想要重建对象可能拥有的任何资源,或者说它被用来重建可能已经丢失的数据库连接时,它非常有用。

__sleep和__wakeup魔术方法的例子

<?php
class userConnection
{
	protected $con;
	private $serverName, $userName,$password,$dbname; 
	public function __construct($serverName, $userName,$password,$dbName)
	{
		$this->server=$serverName;
		$this->username=$userName;
		$this->password=$password;
		$this->dbanme=$dbName;
		$this->connect();
	}
	private function connect()
	{
		$this->con=mysql_connect($this->server,$this->username,$this->password);
		mysql_select_db($this->dbanme,$this->con);
		if (!$this->con)
		{
			die('无法连接: ' . mysql_error());
		}
		echo "连接成功.";
	}
	public function __sleep()
	{
		return array($serverName, $userName,$password,$dbName);
	}
	public function _wakeup()
	{
		this->connect();
	}
	$obj=new userConnection('localhost','root','','mysql');
?>
日期:2020-04-18 01:09:16 来源:oir作者:oir