【问题标题】:set a public variable in laravel model在 laravel 模型中设置一个公共变量
【发布时间】:2015-12-09 08:03:04
【问题描述】:

美好的一天,

我正在尝试将变量发送到模型以在所有函数中使用,而不将其作为参数传递给所有函数, 这是我所做的,但它不起作用,任何人都可以找出问题所在?

 SomethingController.php
   public function store(){
         $user_value = \Request::input('value');  // get value from user
         $somethingObj = new \App\Something(['user_value' => $user_value ]);
         $somethingObj->doSomething();
   }


 Something.php

  public $value;
  public function __constructor($attributes){
      $this->value = $attributes['user_value']; 
  }
  public function doSomething(){
       if($this->value){   
          // this is not working , $value not working also  $this->$value didn't work too
          doSomething();
       }else{
           doOtherThing();
       }
  }

【问题讨论】:

  • Something 是否扩展 Eloquent

标签: php oop laravel model structure


【解决方案1】:

我认为在构造函数中传递值在模型的情况下不起作用。您可以做的是创建一个 setter 方法。

    function setValue($val){
        $this->value = $value;
    }

现在您可以使用 $this->value 在其他方法中访问它。

【讨论】:

    【解决方案2】:

    您应该将 __constructor 重命名为 __construct,它应该可以工作。

    【讨论】:

      【解决方案3】:

      如果您的 Something 模型扩展了 Eloquent,您必须覆盖静态类 create(),如下所示:

      public static function create(array $attributes) 
      {        
          $this = parent::create($data);                
          $this->value = $attributes['value'];
          return $this;
      }
      

      并称它为:

      $somethingObj = \App\Something::create(['user_value' => $user_value ]);
      

      【讨论】:

        猜你喜欢
        • 2010-12-31
        • 1970-01-01
        • 1970-01-01
        • 2011-10-21
        • 1970-01-01
        • 1970-01-01
        • 2016-11-26
        • 2014-05-19
        • 2017-04-27
        相关资源
        最近更新 更多