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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.