php 中如何用 References 实现 method chain ?

2012-08-13 13:59:17 +08:00
 cave
References can produce a chain like what jQuery used:

<?php
$a = new test();
echo ($a -> one() -> two() -> one() -> two() -> one() -> two() -> f);
?>

Result return 29.

如上 test 是如何用 References 实现的?
3752 次点击
所在节点    PHP
11 条回复
Cofyc
2012-08-13 14:09:47 +08:00
public function one() {
// do stuff

}
Cofyc
2012-08-13 14:09:48 +08:00
public function one() {
// do stuff

}
Cofyc
2012-08-13 14:11:27 +08:00
public function one() {
// do stuff
return $this;
}

public function two() {
// do stuff
return $this;
}

// ...

不知道按了什么按键,连发了两次不完整的。。。
cave
2012-08-13 14:18:40 +08:00
@Cofyc 可是这样实现跟References有关系吗?

我以为会是形如:
class test{
public $f;

public function & one(){
……
}

public function & two(){
……
}
}
Cofyc
2012-08-13 14:28:56 +08:00
php 里对象变量存储的就是对象的 reference
不需要 &
Cofyc
2012-08-13 14:30:53 +08:00
jQuery 里写法也是这样的,比如:

// ...
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();

// Add the callback
readyList.add( fn );

return this;
},
// ...
yesmeck
2012-08-13 14:32:10 +08:00
每个方法都 return $this;
cave
2012-08-13 14:52:21 +08:00
也就是说 return $this 是间接的使用了References ?

我以为会有其他的通过References实现method chain的方式

thanks @Cofyc
yesmeck
2012-08-13 15:38:01 +08:00
@cave 你这个代码是在手册下面的评论里看到的吧。你看那个评论时间,在以前 PHP 的对象不是引用传递的所以没办法直接 return $this; 来实现链式调用。
cave
2012-08-13 16:28:03 +08:00
@yesmeck
xcl3721
2012-08-28 10:32:26 +08:00
魔法函数+返回自己即可。
用魔法函数更灵动一些
http://blog.sina.com.cn/s/blog_4a1695ff0100m1yr.html

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/45010

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX