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

报错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行修改为下面内容即可。

c h a r g e s = s e l f : : w h e r e ( ′ m a j o r i d ′ , charges = self::where('major_id', charges=self::where(majorid,student->major_id)->select();

错误代码2:

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

//调用
$charges = StudentCharge::getCharges($student->id);

解决办法2:

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

$sc = new StudentCharge;
$charges = $sc->getCharges($student->id);
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值