-
-
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 "
";<li>$p = new Person();<li>if ( isset( $p->name ) ) {<li> print $p->name;<li>} else {<li> print "nope\n";<li>}<li>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);
- }
- }
立即学习“PHP免费学习笔记(深入)”;
function setAge( $age ) {
- $this->_age = $age;
- }
- }
- print "
";<li>$p = new Person();<li>$p->name = "bob";<li>$p->age = 44;<li>print_r( $p );<li>unset($p->name);<li>print_r( $p );<li>print " 登录后复制 ";
- ?>
-
复制代码
输出结果:
Person Object
(
[_name:Person:private] => BOB
[_age:Person:private] => 44
)
Person Object
(
[_name:Person:private] =>
[_age:Person:private] => 44
)
|