background image

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 会产生一个警告。

演示代码

1:

代码如下

:

<?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 {