Reputation: 461
In my code I have a variable assign of some data inside a switch statement. But that variable not output the data when it calls outside the switch statement. Sample code is here.
switch (some condition){
case 1:
$userid = $receiver->getMessage();
break;
case 2:
break;
}
echo $userid;
how I solve this problem.
Upvotes: 0
Views: 1466
Reputation: 11
You're not doing anything with case 2 or default. If you structure it like this, then it should work.
switch ($condition) {
case 1:
$userId = $receiver->getMessage();
break;
case 2:
$userId = $receiver->someOtherMessage();
break;
default:
$userId = null;
break;
}
At a different point you can validate if the userId has actually been set as well.
Upvotes: -1
Reputation: 27092
Variable declared inside switch
statement is visible outside, of course.
Problem is when isn't declared inside switch, you can avoid it two ways:
$userid = 'default value';
before switch
echo isset($userid) ? $userid : 'default value';
after switch
.Default value can be whatever, if nothing, use empty string.
Upvotes: 2
Reputation: 602
On possible way is to declare the variable before you call the switch statement.
$userid = "";
switch (some condition){
case 1:
$userid = $receiver->getMessage();
break;
case 2:
break;
}
echo $userid;
Upvotes: 0