473,569 Members | 2,782 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Confused about scope of globals in included files

I'm having an issue where what should be global variables are not in
scope and I'm confused as to why.

In Case 1 the variables are not in scope for functions in File2
In Case 2 the varibales are in scope for access in File1's functions
AFTER the include
In Case 3 the varibales are in scope for functionsin File2
Why does case 1 not work but case 3 does? Does case 2 the proper method
to use?

CASE 1:

File1:

switch (OBJ) {
case 1:
include "file2.php"
if Function_In_Fil e2()
....
break;
}

File2:

<?php

$MY_GLOBAL_VARI ABLE = "TEST";

Function Function_In_FIl e()
{
global $MY_GLOBAL_VARI ABLE;
echo $My_GLOBAL_VARI ABLE; /* Produces Notice: Undefined variable:
$My_GLOBAL_VARI ABLE in File2.php on line xx */
}

?>

CASE 2:
File1:

switch (OBJ) {
case 1:
include "file2.php"
if Function_In_Fil e2()
....
break;
}

File2:

<?php

global $MY_GLOBAL_VARI ABLE; $MY_GLOBAL_VARI ABLE = "TEST";

Function Function_In_FIl e()
{
global $MY_GLOBAL_VARI ABLE;
echo $My_GLOBAL_VARI ABLE; /* Displays "TEST" */
}

?>

CASE 3:
File1:

switch (OBJ) {
case 1:
include "file2.php"
echo $MY_GLOBAL_VARA IBLE; /* Displays "TEST" Why does this work and
not case 1? */

}

File2:

<?php

$MY_GLOBAL_VARI ABLE = "TEST";

?>

Feb 22 '06 #1
6 1539
Please post the actual code. It's hard to tell what's wrong with
pseudo-code containing multiple typos. There is no reason for case 1 to
not work. Most likely you just have a spelling error somewhere.

Feb 23 '06 #2
Create_Batch.ph p file

Function Create_Batch($B atch_Number, $EDI_Data)
{
switch( Detect_Type_of_ EDI_File($EDI_D ata) ) {
case "FDX":
include "EDI_Fedex.php" ;
echo "AFTER INCLUDE CHECK COMPANY NAME ($COMPANY_NAME_ ID)<br>";
if ( !Extract_EDI_Da ta($Batch_Numbe r, $EDI_Data) )
return false;
echo "AFTER BATCH CREATION CHECK COMPANY NAME
($COMPANY_NAME_ ID)<br>";
break;
case "DHL":
include "EDI_DHL.ph p";
if ( !Extract_EDI_Da ta($Batch_Numbe r, $EDI_Data) )
return false;
break;
default:
echo "ERROR! Unable to detect EDI file type <BR>";
return false;
break;
}
return !Duplicate_Batc h_Found($Batch_ Number);
}

EDI_Fedex.php file

<?php

include "EDI_STD_Functi ons.php";

$CURRENT_CHARGE = array();

$EDI_REFERENCE = "";

$PAYMENT_TYPE = "WIRE";

$COMPANY_NAME_I D = "FDX";
echo "OUTSIDE FUNCTION CHECK COMPANY NAME($COMPANY_N AME_ID)<br>";
$VENDOR_NUMBER = "97139";

Function Extract_EDI_Dat a($Batch_Number , $EDI_Data)
{
global $COMPANY_NAME_I D;
echo "INSIDE FUNCTION CHECK COMPANY NAME ($COMPANY_NAME_ ID)<br>";
}

OUTPUT:
OUTSIDE FUNCTION CHECK COMPANY NAME(FDX)
AFTER INCLUDE CHECK COMPANY NAME (FDX)
INSIDE FUNCTION CHECK COMPANY NAME ()
AFTER BATCH CREATION CHECK COMPANY NAME (FDX)

If I use the global $COMPANY_NAME_I D; $COMPANY_NAME_I D = "FDX"; it
works for all 4 cases.

I did a FIND "$COMPANY_NAME_ ID" * > search.txt

and here's the output from my entire source directory. There is no
other instances where I use this variable name so I'm completely
baffled as to what is causing this issue. I actually wrote a test case
matching the case 1 and 2 I spoke about above and both functioned
correctly.
---------- CLOSE_BATCH.PHP

---------- CONSTANTS.PHP

---------- CREATE_BATCH.PH P
echo "AFTER INCLUDE CHECK COMPANY NAME ($COMPANY_NAME_ ID)<br>";
echo "AFTER BATCH CREATION CHECK COMPANY NAME
($COMPANY_NAME_ ID)<br>";

---------- CREATE_EDI_TABL ES.PHP

---------- CREATE_WIRE_FOR M.PHP

---------- EDI_DHL.PHP
global $COMPANY_NAME_I D; $COMPANY_NAME_I D = "DHL";
global $COMPANY_NAME_I D, $EDI_REFERENCE, $REMITTANCE_EMA IL_ADDRESS;
echo "Creating remit file for $COMPANY_NAME_I D";
$query = "SELECT BATCHNUM FROM $TABLE_HEADER WHERE COMPID =
'$COMPANY_NAME_ ID' AND PAYREF = '$Pay_Ref' AND PAYDATE = '$Pay_Date'";
echo "ERROR: Nothing to remit for Company: $COMPANY_NAME_I D PayRef:
$Pay_ref Date: $Pay_Date<br>";
$COMPANY_NAME_I D = "DHL";
return ( Build_Header_De tail($Batch_Num ber, $COMPANY_NAME_I D,
$EDI_REFERENCE) );

---------- EDI_FEDEX.PHP
$COMPANY_NAME_I D = "FDX";
echo "OUTSIDE FUNCTION CHECK COMPANY NAME($COMPANY_N AME_ID)<br>";
global $COMPANY_NAME_I D, $REMITTANCE_FIL E_PATH, $REMITTANCE_FIL E_NAME;
echo "Creating remit file for $COMPANY_NAME_I D";
$query = "SELECT BATCHNUM FROM $TABLE_HEADER WHERE COMPID =
'$COMPANY_NAME_ ID' AND PAYREF = '$Pay_Ref' AND PAYDATE = '$Pay_Date'";
echo "ERROR: Nothing to remit for Company: $COMPANY_NAME_I D PayRef:
$Pay_ref Date: $Pay_Date<br>";
global $COMPANY_NAME_I D;
echo "INSIDE FUNCTION CHECK COMPANY NAME ($COMPANY_NAME_ ID)<br>";
return ( Build_Header_De tail($Batch_Num ber, $COMPANY_NAME_I D,
$EDI_REFERENCE) );

---------- EDI_STD_FUNCTIO NS.PHP

---------- FREIGHT_EDI.JS

---------- FREIGHT_EDI.PHP

---------- FREIGHT_EDI_DIS PLAYBATCH.PHP

---------- GENERATE_GL_DAT A.PHP

---------- GET_FEDEX_EDI_F ILES.PHP

---------- OPEN_BATCH.PHP

---------- PAY_VENDOR.PHP

---------- PRINT_PAYMENT_F ORM.PHP

---------- SAVE_BATCH.PHP

---------- SEARCH.TXT

---------- SENDREMIT.BAT

---------- SPLIT_CHARGE.HT ML

---------- TOOLBAR_FREIGHT _EDI.HTML

---------- TOOLBAR_WORK_BA TCH.HTML

---------- VALIDATE_GL_DAT A.PHP

---------- WIRETRANSFERFOR M.HTML

---------- WIRETRANSFERFOR M.HTML.BACKUP

---------- WIRETRANSFORMLA YOUT.XLS

---------- WORK_BATCH.PHP

Feb 23 '06 #3
You need to use the global keyword. When you do an include inside a
function, any global code will end up running inside the scope of that
function.

You might also want to use include_once(), so that you don't end up
with a fatal error (function already defined) when Create_Batch() is
called more than once.

Feb 23 '06 #4
Wescotte wrote:
I'm having an issue where what should be global variables are not in
scope and I'm confused as to why.

In Case 1 the variables are not in scope for functions in File2
In Case 2 the varibales are in scope for access in File1's functions
AFTER the include
In Case 3 the varibales are in scope for functionsin File2
Why does case 1 not work but case 3 does? Does case 2 the proper method
to use?

CASE 1:

File1:

switch (OBJ) {
case 1:
include "file2.php"
if Function_In_Fil e2()
....
break;
}

File2:

<?php

$MY_GLOBAL_VARI ABLE = "TEST";

Function Function_In_FIl e()
{
global $MY_GLOBAL_VARI ABLE;
echo $My_GLOBAL_VARI ABLE; /* Produces Notice: Undefined variable:
$My_GLOBAL_VARI ABLE in File2.php on line xx */
}

?>

CASE 2:
File1:

switch (OBJ) {
case 1:
include "file2.php"
if Function_In_Fil e2()
....
break;
}

File2:

<?php

global $MY_GLOBAL_VARI ABLE; $MY_GLOBAL_VARI ABLE = "TEST";

Function Function_In_FIl e()
{
global $MY_GLOBAL_VARI ABLE;
echo $My_GLOBAL_VARI ABLE; /* Displays "TEST" */
}

?>

CASE 3:
File1:

switch (OBJ) {
case 1:
include "file2.php"
echo $MY_GLOBAL_VARA IBLE; /* Displays "TEST" Why does this work and
not case 1? */

}

File2:

<?php

$MY_GLOBAL_VARI ABLE = "TEST";

?>


Case 1 did not work because you did not specify $MY_GLOBAL_VARI ABLE as
global in the main part of your code (outside your function
Function_in_fil e_2).

Case 2 worked because you did define it as global in the main part of
your code also.

Case 3 works because you're not in any function in either case.

The include "file2.php" adds the code in file2.php right where the
include statement is. It's exactly like removing the include statement
and pasting the contents of file2 in file 1 at that point.

So - in your third case, the result is just like:

switch (OBJ) {
case 1:
$MY_GLOBAL_VARI ABLE = "TEST"; // From file2.php
echo $MY_GLOBAL_VARI ABLE;
}

As to which is the "correct way" - none of the above are good. You
should try to avoid using globals as it ties the code together more.
For instance, what happens if $MY_GLOBAL_VARI ABLE gets a bad value in
it? Where was it changed? Being a global, it could be anywhere.
Rather, pass $MY_GLOBAL_VARI ABLE as a parameter to the function, i.e.
for case 1:

File1:

switch (OBJ) {
case 1:
include "file2.php"
if Function_In_Fil e2($MY_GLOBAL_V ARIABLE)
....
break;
}

File2:

<?php
$MY_GLOBAL_VARI ABLE = "TEST";

Function Function_In_Fil e($var)
{
echo $var;
}
?>

I don't like this - it means File1 depends on a value set in File2 which
also ties things together more. But it does solve the global problem.

You could also use a constant, i.e.

define ("GLOBAL_CONSTA NT", "TEST");

and use GLOBAL_CONSTANT where you have MY_GLOBAL_VARIA BLE, but this only
works if you include one file each run (i.e. don't look and include
multiple files defining GLOBAL_CONSTANT ).

Personally, I think I'd look at how I could restructure the files. But
not knowing your code, I can't recommend how to do it.

BTW - the norm in PHP is to use upper case for constants and lower case
(or mixed upper/lower, depending on your style) for variables, i.e.
$my_global_vari able or $myGlobalVariab le.

I hope this helps.
--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
Feb 23 '06 #5
Here is what I'm actually trying to do. I have several different types
of files the user is loading into the application.
I have several freight vendors and each has a slightly differnet file
type. So I detect the file type and then based on that load a specific
file that sets various constants for this particular vendor and has a
common set of functions.

So something like (sudocode)

$type = Detect_File_Typ e($file);

switch ($type) {
case: "FEDEX"
include "Fedex.php" ;
Create_Batch($B atch_Number, $file);
break;
case: "DHL"
include "DHL.php";
Create_Batch($B atch_Number, $file);
break;
default:
echo "unable to process file";
return false;
break;
}

Fedex.php

include "general_batch_ functions.php";

Define constants

Function Create_Batch()
{
}

other specific functions for FEDEX file processing
DHL.php

include "general_batch_ functions.php";

Define constants

Function Create_Batch()
{
}

other specific functions for DHL file processing

How would you go about doing such a task?

The constants defined in each file aren't needed anymore after the
batch is created.

The only time they are another switch takes place and it's included
again (done for the payment process because most of the constants are
like a remittance address and the bank account numbers to make ACH
payments to and such.) I supose I could simply store these constants in
a database table but because I need specific functions to read the data
it seemed like a better caseto group it all into one file. Any
suggestions on possibly a better design?

Feb 23 '06 #6
Wescotte wrote:
Here is what I'm actually trying to do. I have several different types
of files the user is loading into the application.
I have several freight vendors and each has a slightly differnet file
type. So I detect the file type and then based on that load a specific
file that sets various constants for this particular vendor and has a
common set of functions.

So something like (sudocode)

$type = Detect_File_Typ e($file);

switch ($type) {
case: "FEDEX"
include "Fedex.php" ;
Create_Batch($B atch_Number, $file);
break;
case: "DHL"
include "DHL.php";
Create_Batch($B atch_Number, $file);
break;
default:
echo "unable to process file";
return false;
break;
}

Fedex.php

include "general_batch_ functions.php";

Define constants

Function Create_Batch()
{
}

other specific functions for FEDEX file processing
DHL.php

include "general_batch_ functions.php";

Define constants

Function Create_Batch()
{
}

other specific functions for DHL file processing

How would you go about doing such a task?

The constants defined in each file aren't needed anymore after the
batch is created.

The only time they are another switch takes place and it's included
again (done for the payment process because most of the constants are
like a remittance address and the bank account numbers to make ACH
payments to and such.) I supose I could simply store these constants in
a database table but because I need specific functions to read the data
it seemed like a better caseto group it all into one file. Any
suggestions on possibly a better design?


Well, if you're only going to use them in the Create_Batch() function,
you could put them right in that function.

Or, if you have more than one function using the values and your
Create_Batch function differs between the various types, create classes
for each of the various types, i.e.

class fedex
var $company_id = 'FEDEX';
Create_batch() {
// use as $this->company_id
}
Another_Func () {
...
}
}

class dhl
var $company_id = 'DHL';
Create_batch() {
// use as $this->company_id
}
Another_Func () {
...
}
}

class xyz
var $company_id = 'XYZ';
Create_batch() {
// use as $this->company_id
}
Another_Func () {
...
}
}

Then include all of them in your first file and instantiate an object of
the appropriate type, i.e.

switch ($type) {
case: "FEDEX"
$shipper = new fedex();
break;
case: "DHL"
$shipper = new dhl();
break;
default:
shipper = null;
break;
}

if ($shipper == null)
echo "unable to process file";
else
$shipper->Create_Batch($ Batch_Number, $file);
Much cleaner.

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===
Feb 23 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2907
by: NotGiven | last post by:
I have an file I call using: require_once() In this file I have variables I'd like to use in the calling page and functions called by that page. How can I do this? example:
6
3384
by: Tom | last post by:
I'm tying myself in knots trying to figure out variable scope with constants and include files. This is what I'm doing: A page (index.php) on my website includes a general purpose include file (ini.inc) that declares a constant DAY_NUM. A little later in the file, ini.inc includes another file (b_data.inc) that tries to use DAY_NUM. I'm...
6
2559
by: Andy Baker | last post by:
Hi there, I'm learning Python at the moment and trying to grok the thinking behind it's scoping and nesting rules. I was googling for nested functions and found this Guido quote: (http://www.python.org/search/hypermail/python-1993/0343.html) "This is because nested function definitions don't have access to the local variables of the...
9
4597
by: jfj | last post by:
Hi. Suppose this: ######################## def foo (x): print x f = classmethod (foo)
5
27968
by: William | last post by:
In Peer.h, I have: class Peer { // ... }; In Overseer.h, I have: #include "Peer.h" #include <vector>
165
6760
by: Dieter | last post by:
Hi. In the snippet of code below, I'm trying to understand why when the struct dirent ** namelist is declared with "file" scope, I don't have a problem freeing the allocated memory. But when the struct is declared in main (block scope) it will segfault when passing namelist to freeFileNames().
10
3882
by: m.epper | last post by:
Hi to everybody. First of all sorry for my english, I'm italian. How can I execute a portion of code, in a function, into the global scope? Example: <?php
5
3199
by: Sandra-24 | last post by:
Is there a way in python to add the items of a dictionary to the local function scope? i.e. var_foo = dict. I don't know how many items are in this dictionary, or what they are until runtime. exec statements are difficult for debuggers to deal with, so as a workaround I built my code into a function and saved it in a .py file. The I load...
9
999
by: Pat | last post by:
I have a Globals class. In it, I have a variable defined something like this: remote_device_enabled = bool In one module, I assign True/False to Globals.remote_device_enabled. Once set, this value never changes. In another module, at the top after the imports statements, I tried this:
0
7697
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7612
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7672
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7968
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6283
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5512
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1212
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
937
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.