Dragon
主机之家测评主机之家测评  2019-08-26 17:00 主机之家测评 隐藏边栏 |   抢沙发  169 
文章评分 0 次,平均分 0.0

在 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);

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

发表评论

扫一扫二维码分享