欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP中__set 与 __get使用示例

程序员文章站 2022-04-22 12:57:04
...
  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 )