[资料]PHP中的__set & __get使用

PHP中的__set & __get使用

官方说明

public void __set ( string $name , mixed $value )
public mixed __get ( string $name )
public bool __isset ( string $name )
public void __unset ( string $name )

在给未定义的变量赋值时,__set() 会被调用。

读取未定义的变量的值时,__get() 会被调用。

当对未定义的变量调用 isset() 或 empty()时,__isset() 会被调用。

当对未定义的变量调用 unset()时,__unset() 会被调用。

参数$name是指要操作的变量名称。__set() 方法的$value 参数指定了$name变量的值。

属性重载只能在对象中进行。在静态方法中,这些魔术方法将不会被调用。所以这些方法都不能被 声明为static。 从PHP 5.3.0起, 将这些魔术方法定义为static会产生一个警告。

Demo1

<?php
class Person {
    function __get( $property ) {
        $method = "get{$property}";
        if ( method_exists( $this, $method ) ) {
            return $this->$method();
        }
    }

    function __isset( $property ) {
        $method = "get{$property}";
        return ( method_exists( $this, $method ) );
    }  

    function getName() {
        return "Bob";
    }
                                                                                
    function getAge() {
        return 44;
    }
}
print "<pre>";
$p = new Person();
if ( isset( $p->name ) ) {
    print $p->name;
} else {
    print "nope\n";
}
print "</pre>";
// output: 
// Bob
?>

Demo2

<?php
class Person {
    private $_name;
    private $_age;

    function __set( $property, $value ) {
        $method = "set{$property}";
        if ( method_exists( $this, $method ) ) {
            return $this->$method( $value );
        }
    }
 
    function __unset( $property ) {
        $method = "set{$property}";
        if ( method_exists( $this, $method ) ) {
            $this->$method( null );
        }
    }
                                                                        
    function setName( $name ) {
        $this->_name = $name;
        if ( ! is_null( $name ) ) {
            $this->_name = strtoupper($this->_name);
        }
    }

    function setAge( $age ) {
        $this->_age = $age;
    }
}
print "<pre>";
$p = new Person();
$p->name = "bob";
$p->age  = 44;
print_r( $p );
unset($p->name);
print_r( $p );
print "</pre>";
?>
 Output:
Person Object
(
    [_name:Person:private] => BOB
    [_age:Person:private] => 44
)
Person Object
(
    [_name:Person:private] => 
    [_age:Person:private] => 44
)
原文地址:https://www.cnblogs.com/Athrun/p/php_get_set.html