美文网首页PHP
php魔术方法

php魔术方法

作者: taobao | 来源:发表于2020-12-17 10:13 被阅读0次

PHP 中被称为魔术方法(Magic methods)。在命名自己的类方法时不能使用这些方法名,除非是想使用其魔术功能。有如下函数等:

  • __construct(),
  • __destruct(),
  • __call(),
  • __callStatic(),
  • __get(),
  • __set(),
  • __isset(),
  • __unset(),
  • __sleep(),
  • __wakeup(),
  • __serialize(),
  • __unserialize(),
  • __toString(),
  • __invoke(),
  • __set_state(),
  • __clone()
  • __debugInfo()

1、__sleep() 和 __wakeup()

serialize() 函数会检查类中是否存在一个魔术方法 __sleep()。如果存在,该方法会先被调用,然后才执行序列化操作。此功能可以用于清理对象,并返回一个包含对象中所有应被序列化的变量名称的数组。如果该方法未返回任何内容,则 null 被序列化,并产生一个 E_NOTICE 级别的错误。
__sleep() 方法常用于提交未提交的数据,或类似的清理操作。同时,如果有一些很大的对象,但不需要全部保存,这个功能就很好用。
与之相反,unserialize() 会检查是否存在一个 __wakeup() 方法。如果存在,则会先调用 __wakeup 方法,预先准备对象需要的资源。
__wakeup() 经常用在反序列化操作中,例如重新建立数据库连接,或执行其它初始化操作。

<?php
class Connection 
{
    protected $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()
    {
        return array('server', 'username', 'password', 'db');
    }
    
    public function __wakeup()
    {
        $this->connect();
    }
}
?>

2、__serialize() 和 __unserialize()

serialize() 函数会检查类中是否存在一个魔术方法 __serialize()。如果存在,该方法将在任何序列化之前优先执行。它必须以一个代表对象序列化形式的 键/值 成对的关联数组形式来返回,如果没有返回数组,将会抛出一个 TypeError 错误。
如果类中同时定义了 __serialize() 和 __sleep() 两个魔术方法,则只有 __serialize() 方法会被调用。 __sleep() 方法会被忽略掉。如果对象实现了 Serializable 接口,接口的 serialize() 方法会被忽略,做为代替类中的 __serialize() 方法会被调用。

<?php
class Connection
{
    protected $link;
    private $dsn, $username, $password;

    public function __construct($dsn, $username, $password)
    {
        $this->dsn = $dsn;
        $this->username = $username;
        $this->password = $password;
        $this->connect();
    }

    private function connect()
    {
        $this->link = new PDO($this->dsn, $this->username, $this->password);
    }

    public function __serialize(): array
    {
        return [
          'dsn' => $this->dsn,
          'user' => $this->username,
          'pass' => $this->password,
        ];
    }

    public function __unserialize(array $data): void
    {
        $this->dsn = $data['dsn'];
        $this->username = $data['user'];
        $this->password = $data['pass'];

        $this->connect();
    }
}?>

3、__toString()

__toString() 方法用于一个类被当成字符串时应怎样回应。例如 echo $obj; 应该显示些什么。此方法必须返回一个字符串,否则将发出一条 E_RECOVERABLE_ERROR 级别的致命错误。

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo) 
    {
        $this->foo = $foo;
    }

    public function __toString() {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

4、__invoke()

当尝试以调用函数的方式调用一个对象时,__invoke() 方法会被自动调用。

<?php
class CallableClass 
{
    function __invoke($x) {
        var_dump($x);
    }
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>

以上例程会输出:
int(5)
bool(true)

5、__set_state()

自 PHP 5.1.0 起当调用 var_export() 导出类时,此静态 方法会被调用。
本方法的唯一参数是一个数组,其中包含按 array('property' => value, ...) 格式排列的类属性。

<?php

class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array) // As of PHP 5.1.0
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

?>
以上例程会输出:
object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

5、__debugInfo()

当调用var_dump()函数是,此方法会被掉用

<?php
class C {
    private $prop;

    public function __construct($val) {
        $this->prop = $val;
    }

    public function __debugInfo() {
        return [
            'propSquared' => $this->prop ** 2,
        ];
    }
}

var_dump(new C(42));
?>
以上例程会输出:
object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}

相关文章

  • PHP面试梳理

    PHP php 魔术方法 、魔术常量 php cli autoload , spl_autoload compos...

  • PHP魔术方法

    PHP魔术方法

  • PHP魔术方法

    魔术方法(Magic methods) PHP中把以两个下划线__开头的方法称为魔术方法,这些方法在PHP中充当了...

  • 规则引擎升级版(直接能跑)

    利用了php的魔术方法

  • PHP常用魔术方法

    参考链接:PHP之十六个魔术方法详解

  • PHP简明教程-面向对象基础 1

    PHP简明教程 面向对象基础 1 类中魔术方法 类中魔术方法不能被手动调用,几乎每个魔术方法都有触发时机和参数,P...

  • PHP 魔术方法

    PHP中魔术方法 __construct__destruct__set__get__isset__unset 下面...

  • PHP魔术方法

    总的来说, 有下面几个魔术函数__construct() __destruct() __get() __set(...

  • PHP魔术方法

    概念 PHP中把以两个下划线__开头的方法称为魔术方法,这些方法在PHP中充当了举足轻重的作用。 常见的方法 __...

  • PHP魔术方法

    PHP中把以两个下划线__开头的方法称为魔术方法(Magic methods),这些方法在PHP中充当了举足轻重的...

网友评论

    本文标题:php魔术方法

    本文链接:https://www.haomeiwen.com/subject/ksengktx.html