[英]How to make a variable accessable to the whole controller in laravel
可以说我有一个
其中包含一个功能
public function store($store)
{
$store = (query)->get();
return $store;
}
现在,我希望store
一列可供所有功能使用
$id = $store->id
我希望它可以像这样使用
public function abv()
{
$categories = (query)->where('id','=',$id)->get();
}
我的观点是,它成为整个控制器的全局变量。 我该如何实现?
我不确定这是否是您想要的,但是您可以在Controller protected $id
声明一个受保护的或公共变量,然后在调用store时
public function store($store)
{
$store = (query)->get();
$this->id = $store->id;
return $store;
}
并用于其他功能:
public function abv()
{
$categories = (query)->where('id','=',$this->id)->get();
}
但这仅适用于相同的Controller实例,如果您创建Controller的新实例,则在调用store方法之前将不会设置变量$ id。
您可以在控制器的构造函数中将此值设置为私有属性。
class MyController {
private $id;
public function __construct() {
$this->id = (query)->get();
}
// More controller functions
}
现在,控制器中的任何函数都可以使用$this->id
调用此属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.