Jump to content

PHP Accessing a global variable inside a class method


mweinberger

Recommended Posts

Hi,

 

I have the following files:

 

/index.php

/Scripts/Header.php

/Scripts/ClassContact.php

 

The Header.php is a file that contains other include files and global variables / constants, such as the following:

 

global $MyConstant1 = 100;

 

The header file gets included at the top of every file on the site, such as:

 

require( "./Scripts/Header.php" );

 

The other file, ClassContact.php, is a file that contains a PHP class that the index file instantiates, i.e.:

 

$objContact = new ClassContact();

 

Inside the class there is a public method. I would like to access the global variable, but alas I cannot. I have to re-include the file in the method. Why is that? In this one particular case, I cannot include the specific file again, because the PHP system seems to know of the previous inclusion and now objects, just the variable does not display its contents.

 

I hope that you are following. Thoughts?

 

Thanks in advance,

 

Sarah

If you are going to the trouble of writing a class, do it properly and don't pass it values using the global keyword. Pass values either in the class constructor or using a specific initialization class function.

 

For your existing problem, the global keyword only has meaning when it is used inside of a function. global $MyConstant1 = 100; has no meaning at all. If you have not researched what the global keyword is or how it is used, then don't use it.

I only thought of using the global keyword to solve the problem. Up until about an hour ago or so, I was not prefixing global. I merely want the class member to see a variable defined outside the class. How do I go about that? Is that possible?

 

thanks in advance.

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.