php类知识---魔术方法__toString,__call,__debugInfo

<?php

class mycoach
{
public function __construct($name,$age)
{
$this->name = $name;
$this->age = $age;
echo "upon melancholy hill"." ";
}

public function __toString()
{
#echo时触发,返回一个字符串
return "working hard and party with cpc and cj"." ";
}

public function __debugInfo()
{
#一个诡异的方法,解析一个并不存在的函数,以及它其中的数组,返回一个数组
#该方法必须有两个参数
#var_dump()方法触发
return ['name'=>$this->name,'age'=>$this->age];
}

public function __call($funcname,$myvals)
{
#触发时机,当对象调用一个并不存在的方法时
#第一个参数为函数名,第二个为函数的参数---以数组的形式组成
var_dump($funcname,$myvals);
}

}

$cpc = new mycoach('陈培昌',21);
echo $cpc;
$cpc->wenheiwa();
$cpc->saiwa(["0"=>["name"=>"cpc","age"=>22],"1"=>["name"=>"cj","age"=>20]]);

 输出结果:

upon melancholy hill     #实例化时调用了__construct()方法
working hard and party with cpc and cj   #打印对象时调用了__toString方法
string(8) "wenheiwa"  #对象调用了不存在的方法wenheiwa()执行了__call方法,由于函数没有参数,因此打印空
array(0) {
}
string(5) "saiwa"    #对象调用了不存在的方法saiwa()执行了__call方法,由于函数有参数,因此打印参数----其形式为数组
array(1) {
  [0]=>
  array(2) {
    [0]=>
    array(2) {
      ["name"]=>
      string(3) "cpc"
      ["age"]=>
      int(22)
    }
    [1]=>
    array(2) {
      ["name"]=>
      string(2) "cj"
      ["age"]=>
      int(20)
    }
  }
}

原文地址:https://www.cnblogs.com/saintdingspage/p/10960757.html