YII致命错误:调用非对象的成员函数


YII Fatal Error: Call To A Member Function Of A Non Object

有人能帮我吗?我被这个代码卡住了。

$billing->bookingHeader->getCodeNumber('BKG');

实际上,$billing是一个模型,bookingHeader就是关系。

该行生成错误

Fatal error: Call to a member function getCodeNumber() on a non-object

下面是组件包含的结果。

class MonthlyTransactionActiveRecord extends ActiveRecord
{
    public function getCodeNumber($cnConstant = '')
    {
        $arr = array('I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII');
        $month = $this->cn_month ? $this->cn_month - 1 : 0;
        return sprintf('%02d/%04d/%s/%s/%02d', $this->hotel_id, $this->cn_ordinal, $cnConstant, $arr[$month], $this->cn_year);
    }
}

我调用$billing->bookingHeader->getCodeNumber('BKG');两次(在视图和控制器中),它在视图中没有错误,但当我在控制器中调用它时,它会给我错误。

错误的触发因素是什么?如何解决?非常感谢。

在调用对象的方法之前,请检查对象是否为空。

if($billing->bookingHeader){
  $billing->bookingHeader->getCodeNumber('BKG');
}else{
  echo "bookingHeader is empty";
}