变量模型给出意想不到的' ::'

时间:2017-05-29 22:27:11

标签: php laravel laravel-5.4

所以我想知道如何访问放置在变量

中的模型

控制器:

use App\Models\Test;
use App\Models\Owner;
class mainController extends Controller {

    public function __construct()
    {
       $this->home = new MainHelper();
    }

mainHelper.php:

class MainHelper {
    var $test       = 'App\Models\Test';
    ...
    public static function listTesting(){
        $data = $this->test::where('icons_status', '=', 'active')->orderBy('created_at', 'desc')->take(5)->get();
        return $data;
    }

test.php的

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Test extends Model
{
    protected $table = 'test';
    protected $primaryKey = "id";
    protected $guarded = array('id');
    public $timestamps  = false;
}

但是我收到了这个错误

Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in C:\xampp\htdocs\laravel\app\Helpers\MainHelper.php on line 34

或者我做错了吗?我试图找到一种不使用use App\Model\Test

的方法

3 个答案:

答案 0 :(得分:0)

首先,为什么要将模型分配到变量?,其次,在这一行中:

var $test       = 'App\Models\Test';

您正在分配一个字符串,而不是一个模型,因此显然无法按预期工作。

你能做的是:

var $test       = new App\Models\Test;

然后使用

var $test->where(....)

或在同一指令中执行:

$data = App\Models\Test::where('icons_status', '=', 'active')->orderBy('created_at', 'desc')->take(5)->get();
return $data;

答案 1 :(得分:0)

改变这个:

$this->test::where

为:

$this->test->where

答案 2 :(得分:0)

首先,你尝试通过$ this从静态方法访问到非静态字段,它必须是这样的

class MainHelper
{
   public static $test = 'App\Models\Test';

    public static function listTesting()
    {
       $data = self::$test::where('icons_status', '=', 'active')->orderBy('created_at', 'desc')->take(5)->get();
       return $data;
    }
 }