I have this php function that I created that is basically a switch statement. For each case, the $team_image variable is saved to a different value. It looks a little something like this:
function teamImage($team)
{
switch($team)
{
case "Baltimore Orioles":
$team_image = "orioles";
case "New York Yankees":
$team_image = "yankees";
case "Toronto Blue Jays":
$team_image = "bluejays";
You get the idea. However, when I call on the function and try to use the $team_image variable in other parts of my code, it doesn’t work because apparently, the variable is still undefined. any thoughts?
Thanks,
Lance
As you’re only setting the
$team_imageinside theteamImagefunction, it will only exist with that function’s “scope“. (In general, variables, etc. will always exist in as narrow a scope as possible, which is good in terms of encapsulation. (Encapsulation being a key benefit of object orientated programming, etc. which you may go on to discover as you learn more.)As such, you should return the
$team_imagevalue from theteamImagefunction and set it as follows:An alternative would be to define the
$team_imagevariable within theteamImagefunction as a global by adding the lineglobal $team_image;at the beginning of the function, but this isn’t considered good practice.Additionally, you should
break;each case code block within your switch statement as otherwise you’ll simply end up setting$team_imagewith the value assigned in your final case. (i.e.: If you don’t break each statement, code flow will continue into the next.) See the switch PHP manual page for full details.