Welcome to WebmasterWorld Guest from 50.16.112.199

Forum Moderators: coopster & jatar k

Sharing variables between functions

sharing variables betwee functions

   
2:01 pm on Oct 7, 2009 (gmt 0)

10+ Year Member



Can someone please enlighten this old idiot before I end up jumping off our office roof in frustration.

How I can share an array between multiple functions within a given script? Allow me to explain what I am trying to achieve...

The script processes order files uploaded by suppliers. Whenever the script finds a valid line, it calls a function that starts to build the final order, updating various fields in a main array ($IN['order-code'], $IN['quantity'], etc). Now, depending upon what it finds in the update file, it may call varous validation routines which in turn need to update the main $IN array, depending the options found. Finally, once the order has been built, another function uses the data in the $IN array to write the final order to the main tables.

In practise, there are a couple of different central arrays. I had hoped that declaring each as global at the top of each function would allow the data to be shared and updated by each function - but this doesn't always seem to be the case. Passing the arrays in the function parameters is fine when the data only needs to be read, but makes it cumbersom/unreliable when the function also needs to update any elements of the arrays.

Any help in explaining the best approach - in layman's language please - would be much appreciated.

Thanks in anticipation.

11:43 pm on Oct 7, 2009 (gmt 0)

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



I had hoped that declaring each as global at the top of each function would allow the data to be shared and updated by each function - but this doesn't always seem to be the case.

If your array is global (ie. declared in the global scope and not locally to a function) then this should work. OR, use the $GLOBALS[] superglobal. eg. $GLOBALS['IN']['order-code']

NB: Every function that uses the global variable will need to declare it as global at the start of the function, otherwise a local variable will be created.

 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month