1c7 / VideoList

:us: -> :cn: @糖醋陈皮 翻译的视频列表
https://weibo.com/2004104451
57 stars 11 forks source link

php 魔术方法试验 #50

Open 1c7 opened 9 years ago

1c7 commented 9 years ago

2015-8-17 PHP 版本: 5.5.12

construct(),类的构造函数 destruct(),类的析构函数 call(),在对象中调用一个不可访问方法时调用 callStatic(),用静态方式中调用一个不可访问方法时调用 get(),读取不可访问属性的值时,get() 会被调用 set(),在给不可访问属性赋值时,set() 会被调用 isset(),当对不可访问属性调用isset()或empty()时调用 unset(),当对不可访问属性调用unset()时被调用。 sleep(),执行serialize()时,先会调用这个函数 wakeup(),执行unserialize()时,先会调用这个函数 toString(),类被当成字符串时的回应方法 invoke(),调用函数的方式调用一个对象时的回应方法 set_state(),调用var_export()导出类时,此静态方法会被调用。 clone(),当对象复制完成时调用

1c7 commented 9 years ago

1. __isset()

当对不可访问属性调用isset()或empty()时调用


class A{

    function __isset($a){
        echo $a;
    }

}

$a = new A();

isset($a->sdhwuhduwh);

image

1c7 commented 9 years ago

2. __callStatic()

用静态方式中调用一个不可访问方法时调用


class A{

    // 在对象中调用一个不可访问方法时调用
    public static function __callStatic($a, $b){
        echo $a;
        var_dump($b); 
    }

}

$a = new A();

$a::haha('one','two','three'); 
// 调用 haha 这个不存在的方法, 传入3个参数

image

image

1c7 commented 9 years ago

3. __call()

在对象中调用一个不可访问方法时调用


class A{

    // 在对象中调用一个不可访问方法时调用
    function __call($a, $b){
        echo $a;
        var_dump($b); 
    }

}

$a = new A();

$a->haha('one','two','three'); 
// 调用 haha 这个不存在的方法, 传入3个参数

image

image

1c7 commented 9 years ago

4. __toString()

类被当成字符串时的回应方法


class A{

    function __toString(){
        return 'hello nick';
    }

}

$a = new A();

echo $a; 

image image

1c7 commented 9 years ago

5. __get()

读取不可访问属性的值时,__get() 会被调用


class A{

    function __get($parameter){
        return $parameter;
    }

}

$a = new A();

echo $a->bbbb; 

image

image

1c7 commented 9 years ago

6. __set()

在给不可访问属性赋值时,__set() 会被调用。


class A{

    function __set($a,$b){
        echo $a;
        echo $b;
    }

}

$a = new A();

$a->bbbb = 3;

image

image

1c7 commented 9 years ago

7. __isset()

当对不可访问属性调用 isset() 或 empty() 时调用


class A{

    function __isset($a){
        echo $a;
    }

}

$a = new A();

isset($a->haha);

image

image

1c7 commented 9 years ago

8. __unset()

对不存在的属性调用 unset 时, __unset() 会被调用。


class A{

    function __unset($a){
        echo $a;
    }

}

$a = new A();

unset($a->nice);

image

image