php中类 get set,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:

复制代码 代码如下:

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 "

";

$p = new Person();

if ( isset( $p->name ) ) {

print $p->name;

} else {

print "nope\n";

}

print "

";

// output:

// Bob

?>

演示代码2:

复制代码 代码如下:

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 "

";

$p = new Person();

$p->name = "bob";

$p->age  = 44;

print_r( $p );

unset($p->name);

print_r( $p );

print "

";

?>

输出结果:

Person Object

(

[_name:Person:private] => BOB

[_age:Person:private] => 44

)

Person Object

(

[_name:Person:private] =>

[_age:Person:private] => 44

)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值