Im having problems getting this switch function to work properly:
class Convert
{
public $var;
function Change($var)
{
switch($this->var)
{
case “grapes”:
echo $this->var=“GRAPES”;
break;
case “apple”:
echo $this->var=“APPLE”;
break;
case 1:
echo $this->var=2;
break;
default:
echo “Variable does not exist”;
break;
}
}
}
$i=“apple”;
$test=new Convert();
$test->Change($i);
For some reason Im not passing the argument and I get the default statement. What gives?
what am i doing wrong with that variable?
The parameter var you are using in the Change function is a local variable. $test->var is not being assigned the value you pass in the $test->Change() method call, so when you switch($this->var), you haven’t assigned $this->var the value of $var yet.
I like to use an underscore in my object properties to avoid confusion.
I thought that you can pass any variable as an argument and in this case $i=“apple”. The $var is a public variable so i dont see why i can access it. Thank you for your input.
OK I got it now. Thank you for taking a look at my coding!
You can pass any variable as an argument. My understanding is, however, that you have two different $var variables. The public property var and the local function attribute.When you call the method as you have described, you are assigning the value of $i to the local variable $var, but there isn’t anyplace where you assign $this->var = $var , so to speak.
You can either assign $var to $this->var before you call the switch statement, or you can evaluate $var in the switch statement rather than $this->var
Makes sense. You have to assign that $i variable to something. I feel such a newb but Im learning.
I thought when you pass a variable in your object, it also is passed through the function’s method. So I guess I have to assign it in the class to get passed through the function.