dongrongdao8902
2015-12-09 08:03
浏览 385
已采纳

在laravel模型中设置一个公共变量

Nice Day All,

I'm trying to send a variable to the model to be used in all the function without passing it as a parameter to all function, here is what I have do, but it doesn't work, anyone Can figure out the problem?

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

图片转代码服务由CSDN问答提供 功能建议

美好的一天,

我正在尝试将变量发送到 要在所有函数中使用的模型,而不是将其作为参数传递给所有函数,\我在做什么,但它不起作用,任何人都可以找出问题吗? < pre> SomethingController.php public function store(){ $ user_value = \ Request :: input('value'); //从用户获取价值 $ somethingObj = new \ App \ Something(['user_value'=&gt; $ user_value]); $ somethingObj-&gt; doSomething(); } Something .php public $ value; public function __constructor($ attributes){ $ this-&gt; value = $ attributes ['user_value']; } 公共函数doSomething(){ if($ this-&gt; value){ //这不起作用,$ value不起作用$ this-&gt; $ value也不起作用\ n doSomething(); } else { doOtherThing(); } }

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongmu2026 2015-12-09 08:11
    已采纳

    I think passing a value in constructor doesnt work in case of Models. What you can do instead is to create a setter method.

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

    Now you can use $this->value to access it in other methods.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongzhi7641 2015-12-09 08:54

    You should rename __constructor to __construct and it should work.

    评论
    解决 无用
    打赏 举报
  • dtu1747 2015-12-09 14:58

    If your Something model extends Eloquent you must override static class create(), like this:

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

    And call it:

    $somethingObj = \App\Something::create(['user_value' => $user_value ]);
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题