Jump to content

variable in config.php not recognized in function other file


sleith

Recommended Posts

i wanna ask >.<

i have config variables stored in config.php

i used to include this file in everywhere and that works fine

but i have another file that contains functions used for my site.

i don't know why in these functions, the variable in config.php is not recognized (i have included the config.php)

 

 

example:

 

in config.php

<?php
$MY_NAME="SLEITH";
?>

 

 

in function.php

<?php
  require_once("config2.php");
  function printName(){
  echo  $MY_NAME;
}
?>

 

in index.php

<?php
require_once("config.php");
require_once("function.php");

echo printName();
?>

 

this expected to print 'SLEITH', but it didn't

 

need help >.< thx

Please don't suggest using the global keyword to bring a variable into a function. It is bad programming practice. Any main program variable that is needed inside of a function should be passed as a function parameter in the function call.

Please don't suggest using the global keyword to bring a variable into a function. It is bad programming practice. Any main program variable that is needed inside of a function should be passed as a function parameter in the function call.

 

Really? Oops :S Looks like I've got quite a bit of code rewriting to do then :P

 

----------------

Now playing: Red Hot Chili Peppers - Mellowship Slinky In B Major

via FoxyTunes

thanks for the replies

should i passed it into parameter or declared my config in a class config, which better?

:D

From a general purpose application standpoint, where a configuration file would contain all the configuration settings used by the application (they should actually be defined constants since you don't expect them to change, accidentally or deliberately, during the course of a script's execution) a function that needs to access a configuration setting as part of its' code should actually be a class (encapsulating related functions and data into a single object.) The configuration setting(s) used by any particular class would be passed as parameter(s) when the instance of the class is created/initialized.

 

For a general purpose function (having nothing to do with configuration settings), any value would be passed as a parameter in the function call.

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.