Gopi P
Gopi P

Reputation: 437

Access variable across methods Laravel PHP

Hey all actually I too facing the problem but I couldn't understand any of the above methods. Please help me to understand those stuffs and help t fix my problem.

I have two methods method1 and method2, where I receive some value in method 1 which needs to used in method 2. I created a variable on class level but I couldn't access the variable below is the code snippet.

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.
        }
    }
}

Upvotes: 1

Views: 111

Answers (1)

Joseph
Joseph

Reputation: 6269

because you are in class and you declare a property not a simple variable so when you try to access it from the method in your class you need to add $this

keyword that refer to your class

$this->isChecked

so your code will be like this after editing

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.
           }
     }
}

feel free to check the docs for more info

Upvotes: 1

Related Questions