首頁  >  文章  >  後端開發  >  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 "
    ";</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 )



陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn