国内外VPS
主机测评与优惠

Using $this when not in object context错误原因及解决办法

在php中出现Using $this when not in object context的原因是在静态方法中使用$this或者直接调用非静态的方法。

错误代码1:

  //thinkphp 模型类  class StudentCharge extends Model  {      public static function getCharges($id)      {          $charges = $this->where('major_id',$student->major_id)->select();          return $charges;      }  }    //调用  $charges = StudentCharge::getCharges($student->id);

以上代码就会报Using $this when not in object context错误。

解决办法1:在静态方法中使用self::来代替$this->,将上面代码的第5行修改为下面内容即可。

  $charges = self::where('major_id',$student->major_id)->select();

解决办法2:实例化类后再调用该方法,将上面的调用代码修改为下面方式即可。

  $sc = new StudentCharge;  $charges = $sc->getCharges($student->id);

赞(0)
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《Using $this when not in object context错误原因及解决办法》
文章链接:https://www.liuzhanwu.com/3089.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

登录

找回密码

注册