首页 > 解决方案 > 我的代码中的什么导致了以下错误:PHP 致命错误:未捕获的错误:在 null 上调用成员函数 begin()?

问题描述

我有以下两个类对象和一个接口对象。但是,我越来越

PHP 致命错误:未捕获的错误:在 null 上调用成员函数 begin()

我在这里想念什么?

// First Class

class Template1
{
   protected $convert;

   public function convert()
   {
       echo $this->convert->begin();
   }

   public function setConvert(ITemplate $convert) // Interface is also passed through arguments in this function
   {
       $this->convert = $convert;
   }
};

// Interface

interface ITemplate
{
   public function begin();
};

// Second Class

class Template2 implements ITemplate
{
   private $message;

   public function begin() 
   {
       $this->message = "Hello World!";
       return $this->message;
   }
};

// Creating new objects 

$templateTwoObj = new Template2();

$templateOneObj = new Template1();
$templateOneObj->convert() ;


Hello World  //expected output

标签: phpclassoopinterface

解决方案


你错过了:

$templateOneObj->setConvert($templateTwoObj);

$templateOneObj->convert();

推荐阅读