php __call、__set 和 __get的用法介绍

原创
2016-07-25 08:59:47 880浏览
  1. class foo {
  2. function __call($name,$arguments) {
  3. print("Did you call me? I'm $name!
    ");
  4. print_r($arguments);
  5. print("

    ");
  6. }
  7. function doSecond($arguments)
  8. {
  9. print("Right, $arguments!
    ");
  10. }
  11. }
  12. $test = new foo();
  13. $test->doFirst('no this function');
  14. $test->doSecond('this function exist');
  15. ?>
复制代码

__call 实现“过载”动作 这个特殊的方法可以被用来实现“过载(overloading)”的动作,这样你就可以检查你的参数并且通过调用一个私有的方法来传递参数。

例:使用 __call 实现“过载”动作

  1. class Magic {
  2. function __call($name,$arguments) {
  3. if($name=='foo') {
  4. if(is_int($arguments[0])) $this->foo_for_int($arguments[0]);
  5. if(is_string($arguments[0])) $this->foo_for_string($arguments[0]);
  6. }
  7. }
  8. private function foo_for_int($x) {
  9. print("oh an int!");
  10. }
  11. //by bbs.it-home.org
  12. private function foo_for_string($x) {
  13. print("oh a string!");
  14. }
  15. }
  16. $test = new Magic();
  17. $test->foo(3);
  18. $test->foo("3");
  19. ?>
复制代码

2、__set 和 __get的用法 这是一个很棒的方法,__set 和 __get 方法可以用来捕获一个对象中不存在的变量和方法。 例: __set 和 __get

  1. class foo {
  2. function __set($name,$val) {
  3. print("Hello, you tried to put $val in $name
    ");
  4. }
  5. function __get($name) {
  6. print("Hey you asked for $name
    ");
  7. }
  8. }
  9. $test = new foo();
  10. $test->__set('name','justcoding');
  11. $test->__get('name');
  12. ?>
复制代码

在php编程中,尤其是php面向对象编程中,灵活应用__call、__set 和 __get,可以收到意外的惊喜,建议大家牢固掌握。



声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。