Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在laravel模型中设置公共变量_Php_Oop_Laravel_Model_Structure - Fatal编程技术网

Php 在laravel模型中设置公共变量

Php 在laravel模型中设置公共变量,php,oop,laravel,model,structure,Php,Oop,Laravel,Model,Structure,今天天气很好 我试图向模型发送一个变量,用于所有函数,而不将其作为参数传递给所有函数, 这就是我要做的,但它不起作用,任何人都能解决这个问题 SomethingController.php public function store(){ $user_value = \Request::input('value'); // get value from user $somethingObj = new \App\Something(['user_va

今天天气很好

我试图向模型发送一个变量,用于所有函数,而不将其作为参数传递给所有函数, 这就是我要做的,但它不起作用,任何人都能解决这个问题

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

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

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

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

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

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

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

您应该将uu构造函数重命名为u构造函数,它应该可以工作。

您应该将u构造函数重命名为u构造函数,它应该可以工作。

如果您的
模型扩展了
雄辩的
您必须重写静态类
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 ]);

如果您的
某物
模型扩展了
雄辩
,则必须重写静态类
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 ]);

Something
extend
elount
Something
extend
elount