Laravel 中 Controller访问Model函数/常量

<?php
 // User.php
class User extends Model
{
  const USER_STATUS_ACTIVED = 1; //进行中
  const USER_TYPE_TEST = 'test';  //测试用户
  // 需要在控制器访问, 使用static
  public static function getUserStatus()
  {
    return self::USER_STATUS_ACTIVED;
  }
  public function getUserType()
  {
      return self::USER_TYPE_TEST;
  }
}
// UserController.php
use App\Models\User;
class UserController extends CommonController
{
  public function list()
  {
    // 方式一:
    $status = User::USER_STATUS_ACTIVED;
    User::getUserStatus();
    User::getUserType();  // error: Non-static method App\Models\User::getUserType() should not be called statically
    // 方式二:  可以使用
    $user = new User();
    $status = $user->USER_STATUS_ACTIVED;
    $user->getUserStatus();
    $user->getUserType();  
  }
}

猜你喜欢

转载自www.cnblogs.com/jasonLiu2018/p/11948975.html