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

Link to comment
Share on other sites

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.

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.