微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP从另一个名称空间调用抽象类方法

如何解决PHP从另一个名称空间调用抽象类方法

我有一个 OnboardingConversation ,其中我从命名空间 BotMan \ BotMan \ Messages \ Conversations \ Conversation

调用方法 say
namespace PanObed\Conversations;
use BotMan\BotMan\Messages\Conversations\Conversation;

class OnboardingConversation extends Conversation{

      protected $name;
 
        public function __construct() {

        return $this->run();

        }

      public function run() {

        $this->say("Say hello");

      }
}

一个 BotMan \ BotMan \ Messages \ Conversations \ Conversation

namespace BotMan\BotMan\Messages\Conversations;

use BotMan\BotMan\BotMan;
use BotMan\BotMan\Interfaces\ShouldQueue;
use BotMan\BotMan\Messages\Attachments\Audio;
use BotMan\BotMan\Messages\Attachments\Contact;
use BotMan\BotMan\Messages\Attachments\File;
use BotMan\BotMan\Messages\Attachments\Image;
use BotMan\BotMan\Messages\Attachments\Location;
use BotMan\BotMan\Messages\Attachments\Video;
use BotMan\BotMan\Messages\Incoming\IncomingMessage;
use BotMan\BotMan\Messages\Outgoing\Question;
use Closure;
use Illuminate\Support\Collection;
use Spatie\Macroable\Macroable;

abstract class Conversation
{

     use Macroable;

    /**
     * @var BotMan
     */
    protected $bot;

    public function say($message,$additionalParameters = [])
    {
        $this->bot->reply($message,$additionalParameters);

        return $this;
    }
}

但是有一个问题,当我呼叫 new OnboardingConversation 时,我遇到了以下错误

<br />
<b>Fatal error</b>:  Uncaught Error: Call to a member function reply() on null in C:\xampp\htdocs\panobed\bot\vendor\botman\botman\src\Messages\Conversations\Conversation.PHP:205
Stack trace:
#0 C:\xampp\htdocs\panobed\bot\class\Conversations\OnboardingConversation.PHP(32): BotMan\BotMan\Messages\Conversations\Conversation-&gt;say('Test')
#1 C:\xampp\htdocs\panobed\bot\class\Conversations\OnboardingConversation.PHP(23): PanObed\Conversations\OnboardingConversation-&gt;run()
#2 C:\xampp\htdocs\panobed\bot\index.PHP(27): PanObed\Conversations\OnboardingConversation-&gt;__construct()
#3 [internal function]: {closure}(Object(BotMan\BotMan\BotMan))
#4 C:\xampp\htdocs\panobed\bot\vendor\botman\botman\src\BotMan.PHP(495): call_user_func_array(Object(Closure),Array)
#5 C:\xampp\htdocs\panobed\bot\vendor\botman\botman\src\BotMan.PHP(425): BotMan\BotMan\BotMan-&gt;callMatchingMessages()
#6 C:\xampp\htdocs\panobed\bot\index.PHP(32): BotMan\BotMan\BotMan-&gt;listen()
#7 {main}
  thrown in <b>C:\xampp\htdocs\panobed\bot\vendor\botman\botman\src\Messages\Conversations\Conversation.PHP</b> on line <b>205</b><br />

如果我不使用名称空间 PanObed \ Conversations ,则代码正常。那你能告诉我,我在做什么错吗?

Thx

解决方法

您似乎没有在任何地方设置$this->bot属性。

您应该在OnboardingConversation::__constructor中对其进行初始化。 使用正确的对象初始化$this->bot后,您的代码应该可以调用$this->bot->reply(...)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。