php get的用法,php __call、__set 和 __get的用法介绍

1、__call的用法

PHP5 的对象新增了一个专用方法 __call(),这个方法用来监视一个对象中的其它方法。如果你试着调用一个对象中不存在的方法,__call 方法将会被自动调用。

例:__call

复制代码 代码示例:

class foo {

function __call($name,$arguments) {

print("Did you call me? I'm $name!
");

print_r($arguments);

print("
");

}

function doSecond($arguments)

{

print("Right, $arguments!
");

}

}

$test = new foo();

$test->doFirst('no this function');

$test->doSecond('this function exist');

?>

__call 实现“过载”动作

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

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

复制代码 代码示例:

class Magic {

function __call($name,$arguments) {

if($name=='foo') {

if(is_int($arguments[0])) $this->foo_for_int($arguments[0]);

if(is_string($arguments[0])) $this->foo_for_string($arguments[0]);

}

}

private function foo_for_int($x) {

print("oh an int!");

}

//by www.jbxue.com

private function foo_for_string($x) {

print("oh a string!");

}

}

$test = new Magic();

$test->foo(3);

$test->foo("3");

?>

2、__set 和 __get的用法

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

例: __set 和 __get

复制代码 代码示例:

class foo {

function __set($name,$val) {

print("Hello, you tried to put $val in $name
");

}

function __get($name) {

print("Hey you asked for $name
");

}

}

$test = new foo();

$test->__set('name','justcoding');

$test->__get('name');

?>

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值