Jump to content

[SOLVED] global array access in funtion


NewBob

Recommended Posts

Hi!

Don't quite know if this i an O.O.P question so I'll ask it here.

 

In C++ one can create a global array and then access it from within functions.

I'm in the process of designing a calender class but because it will be in swedish I need

swedish names for the months. This is my solution:

$monthname[1] = "Januari";
$monthname[2] = "Februari";
$monthname[3] = "Mars";
$monthname[4] = "April";
$monthname[5] = "Maj";
$monthname[6] = "Juni";
$monthname[7] = "Juli";
$monthname[8] = "Augusti";
$monthname[9] = "September";
$monthname[10] = "Oktober";
$monthname[11] = "November";
$monthname[12] = "December";

function getNameOfMonth($month)
{
     return $monthname[$month]
}

Because the array is created in the global namespace I thought it would work fine.

However, I get nothing. Not even an error message. I realize I could move the array inside the function

since it's the only one that needs the array. But perhaps other functions will need it aswell later on

and I still would like to know how to make this work

 

Thanks in advance,

/Bob

 

I stumbled upon the solution so I thought I write it here for you people wondering the same thing.

The array must be declared global inside the function so the function knows it should access the global

array and not some array that was created inside the function namespace like so:

function getNameOfMonth($month)
{
     global $monthname;
     return $monthname[$month]
}

Now it works  :)

Link to comment
https://forums.phpfreaks.com/topic/48114-solved-global-array-access-in-funtion/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.