V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
suckli
V2EX  ›  PHP

PHP 5.3 回调函数里面怎么使用this

  •  
  •   suckli · Aug 23, 2013 · 5834 views
    This topic created in 4629 days ago, the information mentioned may be changed or developed.
    貌似是无解啊,试了好多种办法都不行~
    9 replies    1970-01-01 08:00:00 +08:00
    shiny
        1
    shiny  
    PRO
       Aug 23, 2013
    php5.3 不是有闭包吗,可以吗?
    shiny
        2
    shiny  
    PRO
       Aug 23, 2013
    看花眼了,贴下代码看看?
    bixuehujin
        3
    bixuehujin  
       Aug 23, 2013
    $self = $this;
    $func = function() use ($self) {
    //some stuff with $self
    }

    这样就好
    clippit
        4
    clippit  
       Aug 23, 2013
    PHP Changelog:

    5.4.0 $this can be used in anonymous functions.
    suckli
        5
    suckli  
    OP
       Aug 24, 2013 via iPad
    @bixuehujin 这样可以吗?

    @clippit 这个我知道,但是我不能升级啊
    clippit
        6
    clippit  
       Aug 24, 2013   ❤️ 1
    @suckli 语言特性所限,应该没有什么办法吧…… @bixuehujin 的那种办法可能可以使用,但是最多只能访问到public的方法,protected和private肯定不行的
    bombless
        7
    bombless  
       Aug 24, 2013
    让类成员函数来返回闭包不就行了……爱干什么干什么。
    suckli
        8
    suckli  
    OP
       Aug 24, 2013
    @bombless 求例子
    suckli
        9
    suckli  
    OP
       Aug 24, 2013
    @bixuehujin
    @clippit
    试了一下,@bixuehujin 的方式的确靠谱
    这里贴一个简单的例子
    <?php
    class B {
    public function funca() {
    $self = $this;
    $b = function($arg1, $arg2) use($self) {
    echo $arg1;
    echo $arg2;
    $self->funcb();
    };
    echo '123';
    $b('arg1','arg2');
    }

    public function funcb() {
    echo 'echo from b function';
    $this->funcc();
    }

    private function funcc() {
    echo 'echo from c function';
    }
    }
    $test = new B;
    $test->funca();
    ?>
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5775 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 07:17 · PVG 15:17 · LAX 00:17 · JFK 03:17
    ♥ Do have faith in what you're doing.