首页 > 解决方案 > 流明:使用助手获取错误:不在对象上下文中时使用 $this

问题描述

我在 Http 文件夹内的 Helpers 文件夹中创建了这个助手:

<?php
   namespace App\Http\Helpers;
    class CreateRandomId{
        public static function get_id($my_table)
        {
            $id = mt_rand(1000000000, 9999999999); 
            if($this->check_id($id,$my_table)){
                get_id($my_table);
            }
            return $id;
        }
    
        public static function check_id($id,$my_table)
        {
            $table=DB::table($my_table)->where('id',$id)->get();
            if (count($table)==0){
                return false;
            }
            return true;
        }
    }

当我在控制器中调用它时:

$new_user_id = CreateRandomId::get_id('users'); 

它给了我这个错误:Using $this when not in object context 我在函数中删除 $this 我得到了这个错误:Call to undefined function App\Http\Helpers\check_id()

标签: phplaravelthislumen

解决方案


check_id 是一个静态函数,如果你想将它访问到其他函数中,那么你必须使用...

self::check_id($id,$my_table)

推荐阅读