php - 我的代码中的什么导致了以下错误: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
解决方案
你错过了:
$templateOneObj->setConvert($templateTwoObj);
前
$templateOneObj->convert();
推荐阅读
- javascript - top = $this.css("top") 返回一个对象与元素值
- r - 在一段时间内细分一个特殊的日子
- html - 如何创建一个将生成电子邮件的按钮
- java - 当字符是新行的第一个字符时,如何修复正则表达式不匹配?
- npm - 在 Travis 中跳过 npm postinstall 脚本
- angular - 如何以角度编写服务测试
- python - 浮点不可迭代python
- javascript - 如何修复“Jquery 平滑滚动动画”在 Bootstrap 上不起作用
- python-2.7 - Boxplot facet grid 与一列、多行共享 x 变量(字符串)
- r - 在 R 中使用神经网络函数获取错误