【问题标题】:Laravel :: call method in helper class with constructorLaravel :: 使用构造函数调用辅助类中的方法
【发布时间】:2021-05-01 14:19:23
【问题描述】:

正如我在上一个问题中提到的,我是 Laravel 的初学者,因此我需要一些帮助,我必须创建帮助类来为某些表创建随机 Id,我使用表构造函数创建这个类来接收不同的表:

<?php
namespace App\Helpers;

use Illuminate\Support\Facades\DB;

class RandomId
{
    public function __construct($my_table)
    {
        $this->my_table=$my_table;
    }

    public function get_id()
    {
        $id = mt_rand(1000000000, 9999999999); 
        if($this->check_id($id)){
            get_id();
        }
        return $id;
    }

    public function check_id($id)
    {
        $table=DB::table($this->my_table)->where('id',$id)->get();
        if (count($course)==0){
            return false;
        }
        return true;
    }
}

然后我将它作为别名添加到 config/app.php

'RandomId' => App\Helpers\RandomId::class,

现在我想在控制器中调用它,我做了这样的事情但不起作用:

<?php

namespace App\Http\Controllers\course;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Helpers\RandomId;

class Course_controller extends Controller
{
    public function add(Request $request)
    {
       $id=RandomId::get_id('courses');
       dd($id);
    }
}

我收到此错误:Non-static method App\Helpers\RandomId::get_id() should not be called statically

【问题讨论】:

    标签: laravel constructor controller helper


    【解决方案1】:

    这是因为get_id 函数不是静态的。定义静态方法时应添加static关键字:

    public static function get_id()
    {
           ....
    

    【讨论】:

    • 我收到此错误:Using $this when not in object context
    • 您还应该将check_id 定义为静态方法并像这样调用它:self::check_id($id)
    • 非常感谢我所做的一切,在我将 $this->mytable 更改为 self::$mytable 后出现此错误:Access to undeclared static property: App\Helpers\RandomId::$my_table
    • 耶!您的代码存在一些问题。首先,您定义了构造函数,但从未使用过它,并且还使用了静态函数,因此不再需要它。其次,当您定义静态方法时,它不能依赖也不能依赖非静态属性,如$my_table。我建议您将表名作为静态函数的参数。如果有帮助,也不要忘记检查为正确答案
    • 非常感谢,我删除了这个类,只使用带有参数的方法
    猜你喜欢
    • 1970-01-01
    • 2015-01-28
    • 2011-06-28
    • 2019-01-10
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多