views:

49

answers:

4

hi all, i want to create a user defined config file,which contains some variables with constant values, now i want to access those values in many pages of my application.how can use those variables using functions..what is the best way to do this without using classes.

A: 

Well doing it without classes you could use define() to create user based constants to use throughout your application.

EDIT The naming convention for constants are all uppercase chars.

example:

define(DATE, date());

you can call it in your script by calling :

$date = DATE;

http://php.net/manual/en/function.define.php

Alternatively you can save the details in the $GLOBALS array. Remember that this is not completely secure, so use md5() to store passwords or sensitive data.

etbal
md5 is not for storing passwords.
Chris
lol i know that ;) My answer may have been a little ambiguous, sorry bout that. I meant md5() any sensitive data in the $GLOBALS array.
etbal
Globals is neither less nor more secure than using `define`. Also, `md5()` effectively destroys the data that it works on, making it useless except for checking that data stored elsewhere is the same.
Victor Nicollet
A: 

You can define this file somewhere and include it or require it.

require_once("path/to/file/config.php"); 

Any variables within this file are accessible in the script that requires/includes it.

Or you can use define as:

define("TEST", "10");    //TEST holds constant 10 

Now using TEST in all capitals will have the value it was defined as.

Also, if you want them accessible in functions you have three options, pass them as arguments to the function when called or declare as global within function.

//example 1
require_once("path/to/file/config.php"); 
function testFunction($var){
   echo $var." inside my function";   //echos contents of $var 
}

//now lets say a variable $test = 10; was defined in config.php
echo $test;    //displays "10" as it was defined in the config file.  all is good
testFunction($test);  //displays "10 inside my function" because $test was passed to function


//example 2
require_once("path/to/file/config.php"); 
function testFunction2(){
   global $test; 
   echo $test; //displays "10" as defined in config.php 
}

//example 3
define("TEST", "10");
echo TEST; // outputs "10"
//could have these constants defined in your config file as described and used above also! 
Chris
A: 

As you're using constants then define() makes sense but you could maybe use ini files as an alternative instead.

Nev Stokes
A: 

Well there are a couple of ways you can do this

Phill Pafford