Examples of __set and __get usage in PHP

WBOY
Release: 2016-07-25 09:03:05
Original
1065 people have browsed it
  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 "
    ";</li>
    <li>$p = new Person();</li>
    <li>if ( isset( $p->name ) ) {</li>
    <li>    print $p->name;</li>
    <li>} else {</li>
    <li>    print "nopen";</li>
    <li>}</li>
    <li>print "
    ";
  20. // output:
  21. // Bob
  22. ?>

复制代码

演示代码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 "
    ";</li>
    <li>$p = new Person();</li>
    <li>$p->name = "bob";</li>
    <li>$p->age  = 44;</li>
    <li>print_r( $p );</li>
    <li>unset($p->name);</li>
    <li>print_r( $p );</li>
    <li>print "
    ";
  27. ?>

复制代码

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



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template