php中PHP5中的魔术⽅法有哪些?请简述其⽤法

__construct()构造方法,实列化对象后自动执行,是由php自动处理机制调用,只要 用于对象的初始化设置

class  BaseClass  {
   function 
__construct () {
       print 
"In BaseClass constructor\n" ;
   }
}

__desctruct()析构方法,当对象被删除、脚本执行文本、保存对象的变量重新赋值时都会执行此方法,主要用于释放资源.

<?php
class  MyDestructableClass  {
   function 
__destruct () {
       print 
"Destroying "  $this -> name  "\n" ;
   }
}

$obj  = new  MyDestructableClass ();
?>

__set()当一类的外部向类中添加属性时,php的自动处理机制会调用此方法

可用于类外部添加属性的限制

class test{
function __set($name,$value){
$attr=array('name','age');
if (in_array($name,$attr)) {
$this->$name=$value;
}
}
}
$test=new test();
$test->name='ynw';
$test->age='25';
$test->money='5555';
var_dump($test);

__get()当访问一个类中不存在的属性或无法以访问的属性时,会由php自动执行机制自动调用此方法。

可以用于再类外部调用私有属性

class test{
private $one='yang';
private $two='neng';
private $three='weng';
function __get($name){
return $this->$name;
}
}
$test=new test();
echo $test->one;


__tostring当对象被当成字符串输出时,php自动处理机制自动调用此方法

用于提示不能直接输出对象

class test{
function __tostring(){
return "这是一个对象,不能直接输出";
}
}
$test=new test();
header('content-type:text/html;charset=utf-8');
echo $test;

__clone当对象被克隆的时间,php自动处理机制自动调用此方法

class test{
function __clone(){
echo "已经被复制";
}
}
$test=new test();
header('content-type:text/html;charset=utf-8');
$test1=clone($test);

__call()当调用的方法不存在或者没有权限的时候,php自动处理机制调用此方法


class test{
function __call($method,$args){
$var1=$args[0];
$var2=$args[1];
return $var1+$var2;
}
}
$test=new test();

echo $test->method(111,889);

__callstatic()当通过类名调用的静态方法不存在或权限不够时,php自动处理机制调用此方法

通过此方法可以从类外部直接调用私有静态方法

class test{
static private function method1($arr){
$var=$arr[0];
echo $var;
}
static function __callstatic($method,$args){
if (method_exists(new self(),$method)) {
self::$method($args);
}
}
}
test::method1(100);

__sleep()当对象序列化时,php自动处理机制调用此方法

__wakeup()当反序列化得到对象时,php自动处理机制调用此方法



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值