<?php
/*
* php魔术方法
*/
class test{
public $name='hr';
private $rate;//汇率
public $content;
public function __construct($string=null)
{
$this->content=$string;
echo '对象被实例化前调用__construct()<hr/>';
}
public function __toString()
{
return '当对像被当做字符串时,自动调用___toString方法<hr/>';//要用return 返回
}
public function __invoke()
{
echo '当对象被当成方法时,自动调用__invoke方法<hr/>';
}
public function __call($name, $arguments)
{
echo '当对象调用一个不存在的方法时,会自动调用__call方法<br/>';
echo '当前调用的方法名是'.$name.'<br/>';
echo '传递过来的参数是:'.print_r($arguments);
echo '<hr/>';
}
public static function __callStatic($name, $arguments)
{
echo '当静态调用一个不存在的方法时,会自动调用__callSatic方法,注意这个方法要用static修饰<br/>';
echo '当前调用的方法名是'.$name.'<br/>';
echo '传递过来的参数是:'.print_r($arguments);
}
public function __get($name)
{
return '<hr/>读取不可访问属性的值时会自动调用__get方法';
}
public function __set($name, $value)
{
echo '<hr/>在给不可访问属性赋值时,当前要将'.$name.'设置为'.$value;
}
public function __isset($name)
{
echo '<hr/>当对不可访问属性调用 isset() 或 empty() 时,__isset() 会被调用'.$name;
}
public function __unset($name)
{
echo '<hr/>当对不可访问属性调用 unset() 时,__unset() 会被调用'.$name;
}
public function __clone()
{
echo '<hr/>如果有人克隆我,将$name的值从'.$this->name.'改为noName';
$this->name='noName';
}
public function __sleep()
{
$this->content='这是个秘密';
return array('content');
}
public function __wakeup()
{
$this->content='可以看我的秘密';
}
public function __destruct()
{
echo '<hr/>对象的所有引用都被删除或者对象被销毁时调用__destruct()';
}
}
$obj=new test('我爱小红');
echo $obj;//调用__toString()方法
echo $obj();//调用__invoke()方法
$obj->notExistFunction("name","age");//实例化调用一个不存在的方法,自动调用__call
test::notExistFunction("sex","birthday");//静态调用一个不存在的方法,自动调用__callStatic
echo $obj->notExistProperty;//__get方法
$obj->rate=1;//__set
isset($obj->notExistPproperty);//__isset
empty($obj->rate);//__isset()
unset($obj->rate);//__unset();
$obj2=clone $obj;//__clone ,此时 $obj2->name的值为 noName ,貌似还调用了一次__destruct方法
echo '<hr/>'.serialize($obj).'<br/>';//serialize序列化前先调用__sleep()
echo '<pre>';
echo print_r(unserialize(serialize($obj)));//unserialize反序列化前先调用__wakeup(),貌似也调用了一次__destruct()
echo '</pre>';
运行结果:
- 热门文章
- win7中将文件拷贝到虚拟机linux下
- phpexcel设置行高及列宽,背景颜色,
- rabbitmq无法启动
- intellij idea不显示git push按钮
- php7中使用mongodb的aggregate进行
- centos7.4 64位下swoole安装及配置
- laravel页面静态化的方法
- navicate连接mycat报1184错误
- 单点登录sso原理及php实现方式及de
- devops-jenkins容器为pending状态
- 好评文章
- phpexcel设置行高及列宽,背景颜色,
- php7中使用mongodb的aggregate进行
- intellij idea打开文件所在文件夹
- windows下使用MongoDB Compass Com
- win7中将文件拷贝到虚拟机linux下
- laravel 中悲观锁 & 乐观锁的使用
- 单点登录sso原理及php实现方式及de
- navicate连接mycat报1184错误
- rabbitmq无法启动
- laravel整合dingo/api方法步骤:jwt
- 我的项目
- 【github】www.github.com/hurong241
- 【码云】gitee.com/hu_rong/projects
- 【docker hub】hub.docker.com/repositories/hurong241
- 【packagist】packagist.org/users/hurong241/packages
- 站点信息
- 建站时间:2011年
- 文章数:607篇
- 浏览数:940273