$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
的错误引用错误吗?预先感谢您的帮助!
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();
// ...
});
}