当前位置:Gxlcms > PHP教程 > PHP中__set与__get使用示例

PHP中__set与__get使用示例

时间:2021-07-01 10:21:17 帮助过:17人阅读

  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. ";
  28. // output:
  29. // Bob
  30. ?>

演示代码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. ";
  35. ?>

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

人气教程排行