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();  
  }
}

 

 

 

posted on 2019-11-28 11:53  潇潇六月雨  阅读(570)  评论(0编辑  收藏  举报

导航