PHP之十六个魔术方法详细介绍

2019-05-02 17:33:52王旭

注意:

此方法必须返回一个字符串,否则将发出一条 `E_RECOVERABLE_ERROR` 级别的致命错误。

警告:

不能在 __toString() 方法中抛出异常。这么做会导致致命错误。

代码:

<?php
class Person
{
  public $sex;
  public $name;
  public $age;

  public function __construct($name="", $age=25, $sex='男')
  {
    $this->name = $name;
    $this->age = $age;
    $this->sex = $sex;
  }

  public function __toString()
  {
    return 'go go go';
  }
}

$person = new Person('小明'); // 初始赋值
echo $person;

结果:

go go go

那么如果类中没有 __toString() 这个魔术方法运行会发生什么呢?让我们来测试下:

代码:

<?php
class Person
{
  public $sex;
  public $name;
  public $age;

  public function __construct($name="", $age=25, $sex='男')
  {
    $this->name = $name;
    $this->age = $age;
    $this->sex = $sex;
  }
  
}

$person = new Person('小明'); // 初始赋值
echo $person;

结果:

Catchable fatal error: Object of class Person could not be converted to string in D:phpStudyWWWtestindex.php on line 18
很明显,页面报了一个致命错误,这是语法所不允许的。

十二、 __invoke(),调用函数的方式调用一个对象时的回应方法

作用:

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

注意:

本特性只在 PHP 5.3.0 及以上版本有效。

直接上代码:

<?php
class Person
{
  public $sex;
  public $name;
  public $age;

  public function __construct($name="", $age=25, $sex='男')
  {
    $this->name = $name;
    $this->age = $age;
    $this->sex = $sex;
  }

  public function __invoke() {
    echo '这可是一个对象哦';
  }

}

$person = new Person('小明'); // 初始赋值
$person();

查看运行结果:

这可是一个对象哦

当然,如果你执意要将对象当函数方法使用,那么会得到下面结果:

Fatal error: Function name must be a string in D:phpStudyWWWtestindex.php on line 18

十三、 __set_state(),调用var_export()导出类时,此静态方法会被调用。

作用:

自 PHP 5.1.0 起,当调用 var_export() 导出类时,此静态方法会被自动调用。

参数:

本方法的唯一参数是一个数组,其中包含按 array('property' => value, ...) 格式排列的类属性。

下面我们先来看看在没有加 __set_state() 情况按下,代码及运行结果如何:

上代码:

<?php
class Person
{
  public $sex;
  public $name;
  public $age;

  public function __construct($name="", $age=25, $sex='男')
  {
    $this->name = $name;
    $this->age = $age;
    $this->sex = $sex;
  }

}

$person = new Person('小明'); // 初始赋值
var_export($person);

								 
			 
相关文章 大家在看