You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BotMan框架Conversation类ask方法回调中$this引用错误的解决求助

解决BotMan Conversation中ask回调$this指向错误的问题

这个问题源于PHP匿名函数的作用域特性:默认情况下,匿名函数不会继承外部上下文的$this,而BotMan的ask方法内部会创建InlineConversation实例,导致回调里的$this指向该实例而非你的自定义Conversation类。

方法1:使用use捕获外部$this

在匿名函数定义时,通过use关键字引入外部的$this,并用变量保存后在回调中使用:

use BotMan\BotMan\BotMan;
use BotMan\BotMan\Messages\Conversations\Conversation;

class DepositConversation extends Conversation
{
    protected $amount;

    public function askAmount()
    {
        $self = $this;
        $this->ask('What is the amount you want to deposit?', function($answer) use ($self) {
            $self->amount = $answer->getText();
            // 调用后续方法,比如askPaymentMethod
            $self->askPaymentMethod();
        });
    }

    public function askPaymentMethod()
    {
        $this->ask('Which payment method do you prefer?', function($answer) {
            // 支付方式处理逻辑
        });
    }
}

方法2:使用PHP箭头函数(PHP 7.4+)

箭头函数会自动继承外部上下文的$this,写法更简洁:

use BotMan\BotMan\BotMan;
use BotMan\BotMan\Messages\Conversations\Conversation;

class DepositConversation extends Conversation
{
    protected $amount;

    public function askAmount()
    {
        $this->ask('What is the amount you want to deposit?', fn($answer) => [
            $this->amount = $answer->getText(),
            $this->askPaymentMethod()
        ]);
    }

    public function askPaymentMethod()
    {
        $this->ask('Which payment method do you prefer?', fn($answer) => {
            // 支付方式处理逻辑
        });
    }
}

注意:箭头函数需要PHP 7.4及以上版本支持,若项目环境版本较低,优先使用第一种方法。

内容的提问来源于stack exchange,提问作者Maestro jims

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:52:34