View Full Version : accessing global variables within a class
07-30-2007, 06:09 PM
me document set up is as follows
now class.php has a class with many functions -- within these functions how can I access variables and arrays that were set within config.php?
07-30-2007, 06:19 PM
The whole idea of OO is strict scoping/encapsulation, so to obey these OO laws of encapsulation you must pass variables into the methods of the class as you would pass variables to a normal non-OO function.
07-30-2007, 06:21 PM
You could try, when creating variables in config.php... instead of making ordinary variables, make session variables.
$username = "Jordan";
$_SESSION['username'] = "Jordan";
//These are the same thing, however I can only access $username within this file.
//I can use $_SESSION['username'] in any file.
echo $username; //Returns nothing
echo $_SESSION['username']; //Returns Jordan
NOTE: You must start every page which uses $_SESSION with "session_start()" (without the quote marks).
PHP REFERENCE: http://uk.php.net/session
07-30-2007, 06:37 PM
I'll bet your config file contains items that are actually CONSTANTs and don't change during the course of program execution. Variables by definition exits so that their value can be changed during the course of program execution.
Beyond using constants, heed Fumigator's advice. The purpose of functions (within a class or not) are to allow you to reuse code. By needing to setup a specifically named variable, instead of passing all needed values as parameters to the function call, you are creating a situation where you can have conflicting variable names and your function/class code cannot simply be reused wherever you want without making sure that you have not used the same name variable for some other purpose.
07-30-2007, 06:38 PM
is there anyway to reference them in the class without session variables
07-30-2007, 06:47 PM
they are not constants but if I made them into constants it would work?
07-30-2007, 06:54 PM
Yes, contants are global.
constants and globals are often a sign of badly structured code, keep their use to an absolute minimum. Things you assume are constant may well one day not be, and refactoring can become very difficult.
If you've got lots of config information, then wrap it in a Config object and pass that into your other objects. The Zend Framework contains a set of classes that will do this, that can run off either a php array, of from ini or xml files: http://framework.zend.com/manual/en/zend.config.html
Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.