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 {
print "nope\n";
}
print "</pre>";
// output:
// Bob
?>
演示代码2:
<?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>";
?>
输出结果:
Person Object
(
[_name:Person:private] => BOB
[_age:Person:private] => 44
)
Person Object
(
[_name:Person:private] =>
[_age:Person:private] => 44
)
您可能感兴趣的文章:
php中__get()和__set魔术方法的用法举例
php入门教程(十四) php面向对象中的魔术方法 __set()、__get()、__isset() 与 __unset()
php __call、__set 和 __get的用法介绍
PHP中__set 与 __get使用示例
正确理解 PHP 的重载
PHP5试用(二)
PHP学习之外部调用类的私有属性
php中__get()和__set()用法介绍
如何理解php重载
魔术方法__get()和__set()详解