BotMan Conversation 的询问方法回调函数中对 $this 的引用不正确

问题描述 投票:0回答:1
我在 PHP 中使用 BotMan 框架创建聊天机器人,并且遇到了一个问题,在与 BotMan 的 Conversation 类的 Ask 方法一起使用的回调函数中错误引用了

$this

我创建了一个扩展 Conversation 类的 DepositConversation 类,并且定义了两个方法

askAmount()

askPaymentMethod()
,用于向用户提问。但是,当我在回调函数内调用 $this(ask 方法的第二个参数)时,
$this
 引用不正确,指的是 
BotMan\BotMan\Messages\Conversation\InlineConversation
 而不是 
DepositConversation

这是我的代码摘录:

use BotMan\BotMan\BotMan; use BotMan\BotMan\Messages\Conversations\Conversation; class DepositConversation extends Conversation { // ... public function askAmount() { $this->ask('What is the amount you want to deposit?', function($answer) { // $this refers to BotMan\BotMan\Messages\Conversation\InlineConversation // instead of DepositConversation $this->amount = $answer->getText(); // ... }); } // ... }
我希望 

$this

 引用 DepositConversation 的实例,以便我可以访问类属性并执行其他操作。然而,它似乎并没有达到预期的效果。

有人以前遇到过这个问题或者知道如何解决 BotMan Conversation 的 Ask 方法的回调函数中对

$this

 的错误引用错误吗?预先感谢您的帮助!

php laravel chatbot botman
1个回答
0
投票
可能

ask

 方法的 
Closure
 函数通过使用 
$this
 绑定到另一个 
\Closure:bind

这些用例中有一个简单的技巧,使用

$that

public function askAmount() { $that = $this; $this->ask('What is the amount you want to deposit?', function($answer) use ($that) { $that->amount = $answer->getText(); // ... }); }
    
© www.soinside.com 2019 - 2024. All rights reserved.