PHP中__set 与 __get使用示例

php中文网
发布: 2016-07-25 09:03:05
原创
1263人浏览过
  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>$p = new Person();<li>if ( isset( $p->name ) ) {<li>    print $p->name;<li>} else {<li>    print "nope\n";<li>}<li>print "
    登录后复制
    ";
  20. // output:
  21. // Bob
  22. ?>
复制代码

演示代码2:

  1. class Person {

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

    芦笋演示
    芦笋演示

    一键出成片的录屏演示软件,专为制作产品演示、教学课程和使用教程而设计。

    芦笋演示 34
    查看详情 芦笋演示
  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. }

    立即学习PHP免费学习笔记(深入)”;

  22. function setAge( $age ) {

  23. $this->_age = $age;
  24. }
  25. }
  26. print "
    ";<li>$p = new Person();<li>$p->name = "bob";<li>$p->age  = 44;<li>print_r( $p );<li>unset($p->name);<li>print_r( $p );<li>print "
    登录后复制
    ";
  27. ?>
复制代码

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



PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号