0

I have this variable on class/Controller level $songRating and i am calling this method through ajax, when i first time call this method it runs the if block which is good. and now $songRating should be 1. But this is not a case. When i call this method it again runs the if block. Dont know why :/

public $songRating;
public function GetHighRatedSong()
{
        if($this->songRating == null){
            $this->songRating=1;
        }else{
            $this->songRating=2;
        }

        return response()->json($this->songRating);
}
Sameer Kamran
  • 227
  • 4
  • 15
  • if by the next time you call this method you mean the next "request" then it really wouldn't matter what you set any instance variable to before as these are all new instance variables at this point – lagbox Aug 09 '18 at 07:28
  • im from c# background and in that we are allowed to do this.if we have any class level variable then after changing its value from method that variable saves this variable for a single request.. im calling this method using ajax.. – Sameer Kamran Aug 09 '18 at 07:42
  • As lagbox said, you should save the $this->songRating attribute somewhere (may be update the Model if this is inside a Model object). In PHP, each request runs in a completely different thread, it will not know what happened in your previous request unless you save the data somewhere. – Ahmed Shefeer Aug 09 '18 at 07:45

2 Answers2

2

Try with Replacing

$this->songrating=1;

to

$this->songRating=1; # song+Rating != song+rating

Read PHP & Case Sensitivity

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
0

It's because everytime you call that function or make a new instantiation to the class, it will automatically reset to it's original value. Try to use service container