在 laravel 模型中设置一个 public 变量
set a public variable in laravel model
美好的一天,
我正在尝试将一个变量发送到模型以在所有函数中使用,而不是将其作为参数传递给所有函数,
这是我所做的,但它不起作用,任何人都可以找出问题吗?
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 在其他方法中访问它。
您应该将 __constructor 重命名为 __construct,它应该可以工作。
如果您的 Something
模型扩展 Eloquent
,您必须覆盖静态 class 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 ]);
美好的一天,
我正在尝试将一个变量发送到模型以在所有函数中使用,而不是将其作为参数传递给所有函数, 这是我所做的,但它不起作用,任何人都可以找出问题吗?
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 在其他方法中访问它。
您应该将 __constructor 重命名为 __construct,它应该可以工作。
如果您的 Something
模型扩展 Eloquent
,您必须覆盖静态 class 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 ]);