suckli
V2EX  ›  PHP

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

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

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

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

    @clippit 这个我知道,但是我不能升级啊
    clippit
    clippit
    Aug 24, 2013❤️1
    6
    @suckli 语言特性所限,应该没有什么办法吧…… @bixuehujin 的那种办法可能可以使用,但是最多只能访问到public的方法,protected和private肯定不行的
    bombless
    bombless
    Aug 24, 2013
    7
    让类成员函数来返回闭包不就行了……爱干什么干什么。
    suckli
    suckli
    OP
    Aug 24, 2013
    8
    @bombless 求例子
    suckli
    suckli
    OP
    Aug 24, 2013
    9
    @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   ·   Privacy   ·   Solana   ·   1808 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 15:54 · PVG 23:54 · LAX 07:54 · JFK 10:54
    ♥ Do have faith in what you're doing.