V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
cave
V2EX  ›  PHP

php 中如何用 References 实现 method chain ?

  •  
  •   cave · 2012-08-13 13:59:17 +08:00 · 3730 次点击
    这是一个创建于 4245 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 实现的?
    11 条回复    1970-01-01 08:00:00 +08:00
    Cofyc
        1
    Cofyc  
       2012-08-13 14:09:47 +08:00
    public function one() {
    // do stuff

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

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

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

    // ...

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

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

    public function & one(){
    ……
    }

    public function & two(){
    ……
    }
    }
    Cofyc
        5
    Cofyc  
       2012-08-13 14:28:56 +08:00
    php 里对象变量存储的就是对象的 reference
    不需要 &
    Cofyc
        6
    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
        7
    yesmeck  
       2012-08-13 14:32:10 +08:00
    每个方法都 return $this;
    cave
        8
    cave  
    OP
       2012-08-13 14:52:21 +08:00
    也就是说 return $this 是间接的使用了References ?

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

    thanks @Cofyc
    yesmeck
        9
    yesmeck  
       2012-08-13 15:38:01 +08:00
    @cave 你这个代码是在手册下面的评论里看到的吧。你看那个评论时间,在以前 PHP 的对象不是引用传递的所以没办法直接 return $this; 来实现链式调用。
    cave
        10
    cave  
    OP
       2012-08-13 16:28:03 +08:00
    @yesmeck
    xcl3721
        11
    xcl3721  
       2012-08-28 10:32:26 +08:00
    魔法函数+返回自己即可。
    用魔法函数更灵动一些
    http://blog.sina.com.cn/s/blog_4a1695ff0100m1yr.html
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1547 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:11 · PVG 01:11 · LAX 10:11 · JFK 13:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.