PHP variable scope in modules

No replies
steve5
Offline
Last seen: 3 years 51 weeks ago
Joined: 2015-03-03

Is there a way to define a variable in a module (here, in a module using the Form API) that is accessible by multiple functions within that module? Something like this:

$large_array_with_lots_of_elements = array( "foo" => 1, "bar" => 2);

function a_simple_form($form, &$form_state) {
  $foo = $large_array_with_lots_of_elements["foo"];
  // etc...
}

function a_simple_form_validate($form, &$form_state) {
  $bar = $large_array_with_lots_of_elements["bar"];
  // etc...
}

The above code would fail with " Notice: Undefined variable: large_array_with_lots_of_elements". Declaring $large_array_with_lots_of_elements as "global" appears to be too broad and comes back with an empty value, rather than the value declared in the module. There doesn't seem to be a way to get either the module scope, or just the parent scope, where $large_array_with_lots_of_elements is declared.

I need my validation and submission functions, as well as the form-bulding code, to all have access to shared variables declared at the module level. (The use keyword appears to only work with closures assigned to variables, not to generic function declarations.)

Is there either a way to do that, or a different way to think about the problem? I'm not a PHP expert, obviously, but in most other languages I work in, this is easy and straightforward - the above (psuedo)code would just work. Thanks for any tips.

Add to playlist

Add to , or

Add to new playlist:

Add to playlist
This is a member-only feature
But, it's easy to become a member

Add to cart:


Loading...
Contact us

Below are the supported keyboard shortcuts for our video player.

space
Start / stop video
shift
Go to next video
shift
Go to previous video
Increase or decrease player speed by 20%
Skip ahead or go back by 15 seconds
1...9
Jump to a percentage (2 is 20%, for example)
f
Toggle full screen
Videos Pricing More Search
BuildAModule Logo Icon BuildAModule Logo Icon
Become a member!
$29
1 month
$156
6 months
10% off
$276
12 months
20% off
All memberships come with the following:
24 / 7 access to the entire 1800+ video library
An innovative video player with a rolling transcript
Extensive Drupal and cross-platform training
A thorough and thoughtful training style
Progress tracking
Take notes on specific video sections
Intuitive multi-user management
How many users?
user
Go solo with a single user, or give multiple team members access through one account and get discounts by bundling multiple users into a single membership.