cave
V2EX  ›  PHP

php 中如何用 References 实现 method chain ?

  •  
  •   cave · Aug 13, 2012 · 5174 views
    This topic created in 5199 days ago, the information mentioned may be changed or developed.
    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 replies  •  1970-01-01 08:00:00 +08:00
    Cofyc
    Cofyc
    Aug 13, 2012
    1
    public function one() {
    // do stuff

    }
    Cofyc
    Cofyc
    Aug 13, 2012
    2
    public function one() {
    // do stuff

    }
    Cofyc
    Cofyc
    Aug 13, 2012
    3
    public function one() {
    // do stuff
    return $this;
    }

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

    // ...

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

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

    public function & one(){
    ……
    }

    public function & two(){
    ……
    }
    }
    Cofyc
    Cofyc
    Aug 13, 2012
    5
    php 里对象变量存储的就是对象的 reference
    不需要 &
    Cofyc
    Cofyc
    Aug 13, 2012
    6
    jQuery 里写法也是这样的,比如:

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

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

    return this;
    },
    // ...
    yesmeck
    yesmeck
    Aug 13, 2012
    7
    每个方法都 return $this;
    cave
    cave
    OP
    Aug 13, 2012
    8
    也就是说 return $this 是间接的使用了References ?

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

    thanks @Cofyc
    yesmeck
    yesmeck
    Aug 13, 2012
    9
    @cave 你这个代码是在手册下面的评论里看到的吧。你看那个评论时间,在以前 PHP 的对象不是引用传递的所以没办法直接 return $this; 来实现链式调用。
    cave
    cave
    OP
    Aug 13, 2012
    10
    @yesmeck 恩
    xcl3721
    xcl3721
    Aug 28, 2012
    11
    魔法函数+返回自己即可。
    用魔法函数更灵动一些
    http://blog.sina.com.cn/s/blog_4a1695ff0100m1yr.html
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1449 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:07 · PVG 00:07 · LAX 08:07 · JFK 11:07
    ♥ Do have faith in what you're doing.