首页  >  文章  >  后端开发  >  PHP中__set 与 __get使用示例

PHP中__set 与 __get使用示例

WBOY
WBOY原创
2016-07-25 09:03:051066浏览
  1. class Person {

  2. function __get( $property ) {
  3. $method = "get{$property}";
  4. if ( method_exists( $this, $method ) ) {
  5. return $this->$method();
  6. }
  7. }
  8. function __isset( $property ) {

  9. $method = "get{$property}";
  10. return ( method_exists( $this, $method ) );
  11. }
  12. function getName() {

  13. return "Bob";
  14. }
  15. function getAge() {
  16. return 44;
  17. }
  18. }
  19. print "
    ";
  20. $p = new Person();
  21. if ( isset( $p->name ) ) {
  22. print $p->name;
  23. } else {
  24. print "nope\n";
  25. }
  26. print "";
  27. // output:
  28. // Bob
  29. ?>
复制代码

演示代码2:

  1. class Person {

  2. private $_name;
  3. private $_age;
  4. function __set( $property, $value ) {

  5. $method = "set{$property}";
  6. if ( method_exists( $this, $method ) ) {
  7. return $this->$method( $value );
  8. }
  9. }
  10. function __unset( $property ) {
  11. $method = "set{$property}";
  12. if ( method_exists( $this, $method ) ) {
  13. $this->$method( null );
  14. }
  15. }
  16. function setName( $name ) {
  17. $this->_name = $name;
  18. if ( ! is_null( $name ) ) {
  19. $this->_name = strtoupper($this->_name);
  20. }
  21. }
  22. function setAge( $age ) {

  23. $this->_age = $age;
  24. }
  25. }
  26. print "
    ";
  27. $p = new Person();
  28. $p->name = "bob";
  29. $p->age = 44;
  30. print_r( $p );
  31. unset($p->name);
  32. print_r( $p );
  33. print "";
  34. ?>
复制代码

输出结果: Person Object ( [_name:Person:private] => BOB [_age:Person:private] => 44 ) Person Object ( [_name:Person:private] => [_age:Person:private] => 44 )



声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn