首页 > 解决方案 > 跨方法访问变量 Laravel PHP

问题描述

嘿,实际上我也面临这个问题,但我无法理解上述任何方法。请帮助我理解这些东西并帮助解决我的问题。

我有两个方法method1和method2,我在方法1中收到一些需要在方法2中使用的值。我在类级别创建了一个变量,但我无法访问下面的变量是代码片段。

class testController extends controller
{
    public $isChecked = false;
    public $isSelectedValue = 0;

    public function ValidateValue(Request $req)
    {
        $isChecked = $req->checked;
        $isSelectedValue = $req->value;
    }

    public function UsethoseValues()
    {
        if ($isChecked) { // I can't use the variable here it throws run time error. I need help on this please help.
        }
    }
}

标签: phplaravel-5

解决方案


因为您在class其中并且声明了一个属性而不是简单的变量,所以当您尝试从您的方法中访问它时,class您需要添加$this

引用您的班级的关键字

$this->isChecked

所以你的代码在编辑后会是这样的

class testController extends controller { 
        public $isChecked = false;
        public $isSelectedValue = 0;
public function ValidateValue(Request $req) {
        $this->isChecked = $req->checked;
        $this->isSelectedValue = $req->value;
     }
public function UsethoseValues() {
        if($this->isChecked) { // I can't use the variable here it throws run time error. I need help on this please help.
           }
     }
}

随时查看文档以获取更多信息


推荐阅读