How to use variables from php file where require/include is declared - php

So basically, I have a config.php file for connecting to the mysql database, and a functions.php file that includes some functions. In all my files (eg. index, login, register), I use the line require('config.php'); and inside config.php I have this line require('functions.php'); for including the config + functions together using the line require('config.php'); in my index, login, and register.php files.
So basically my problem is, the variables that I've declared in config.php are not recognized inside functions.php. How do I make it work?
Thanks in advance.

Use the global statement to declare variables inside functions as global variables.
function myfunction() {
global $myvar; // $myvar set elsewhere can be read within this function
// and if its value changes in this function, it changes globally
}

You can use global variavlename or $GLOBAL['variavlename without $']
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a;
$a = $a + $GLOBALS['b'];
}
Sum();
echo $a;
?>

It's very likely your functions don't work because their scope does not include the variables you are trying to use.
First, make sure functions.php is being included after the variables are set
Also, make your functions Public Functions, OR, declare global variables inside functions by doing this:
$testVariable = "test";
function testFunction() {
global $testVariable;
}

Related

global variables scope in php

I didn't understand this sentence from php.net:
Note:
Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.
what does it mean? can anyone demonstrate briefly?
Global Variables:
In contrast to local variables, a global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name.
Example
$somevar = 15;
function addit(){
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
Output
Somevar is 16
"It can be used if the file is included from inside a function" means that it will even work like this:
page.php
<?php
global $d;
$d = "HI";
?>
index.php
<?php
getpage();
function getpage(){
include 'page.php';
echo $d;
}
?>

Variable accessibility with require_once/ob_start()

Maybe I'm just tired or just am simply confused, but I'm having a strange issue dealing with some require_once() calls and ob_start().
Basic Structure:
Top of Main.php:
require_once 'config.php'; // includes variable $A = "bar", and Function "foo"
function getPage(){
ob_start();
include 'some_file.php';
$html = ob_get_clean();
echo $html;
die();
}
getPage();
some_file.php
require_once 'config.php'; // includes same config file
var_dump($A); // NULL
foo(); // runs, returns correct value
Config.php
$A = 'bar';
function foo(){
return "FOO";
}
So, what is wrong here? I'm including a file while buffering output. The required file config.php holds a variable and function. When including some_file.php during the buffer, the variable $A is apparently NOT set/accessible. The function foo CAN execute.
The documentation says:
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
Your provided code does not illustrate the problem that you're describing. When I run it as-is, it correctly shows that the variable is defined.
That being said, the thing to remember is that what looks like a global variable in an included file actually ends up in the scope of the function that's calling it. So if the first time require_once() is called is from a function, the $A variable is scoped to the function - and disappears when the function returns, just like any other variable defined inside the function.
If you absolutely must define a global variable inside an included file (are you sure? really?), make sure you only include that file from the global scope - not from within a function. If you need to access the variable from within a function, include the file outside the function, and then use the global keyword to access the variable from within the function.

Using require/require_once() in a functions file

my functions.php file is just a placeholder for many different functions. I have another file settings.php that I use to store different settings. Some of the functions in functions.php will need to access some of the variables in settings.php, so I tried:
require("settings.php")
on top of the functions.php file, but that does not seem to give my functions access to the variable in settings.php. I need to put require("settings.php") in every function separately.
Is there a way I can declare the variables in settings.php to be accessible globally to all functions defined in functions.php?
Thank you,
You need to modify your functions in functions.php to use global variables defined in settings.php.
Inside settings.php;
$var1 = "something";
$var2 = "something else";
By using the global keyword:
function funcName() {
global $var1;
global $var2;
// Rest of the function...
}
Or more preferably, using the $GLOBALS[] superglobal array. Any variables declared at global scope, like I assume your settings.php vars are, will be included as array keys in $GLOBALS[]. It's a little better for readability than using the global keyword inside each function.
function funcName() {
$y = $GLOBALS['var1'];
$x = $GLOBALS['var2'];
// Etc...
}
Although you've set these variables in your settings.php file, when you try to reference them in your functions it won't work. This is because variables in functions a locally scoped to the function.
To access these global variables you need to use the global keyword to bring your global variables into scope.
For example:
// Declared in settings.php
$x = 1234;
// One of your functions
function MyFunc()
{
global $x;
DoSomething($x);
}
You need to do this for every function where $x is accessed.
For more information see:
Variable scope - php.net docs
I do not know the details of your issue, but you may wish to use require_once() within each function. This seems to be better idea than using some global variables.
You're thinking global variables.
However that's not the best way to go.
Can you perhaps create a class?
class SomeClass
{
private $settings;
function __construct()
{
require_once($settings);
$this->settings = $variable(s) from settings file
}
function some_function()
{
print($this->settings['something']);
}
}

Help with include function

Im trying to make a simple template system in PHP. I'm new to PHP, so it's nothing serious. I have some problems though:
A regular include works:
$variable = "test";
include("templates/news.html");
But this won't:
This says $variable is undefined:
$variable = "test";
getTemplate("news");
The Function:
function getTemplate($tpl) {
$file = "templates/$tpl.html";
if (file_exists($file))
return include($file);
return false;
}
news.html
<h1>php echo $variable</h1>
the function works and includes the page but it dont write out the variables
I include the function on top of all pages.
Thanks in advance!
With the extract function, you can define different variables from an array.
You can make it like this:
$vars = array('var1' => "value1", 'var2' => "value2");
function getTemplate($tpl, $vars) {
$file = "templates/$tpl.html";
extract($vars, EXTR_SKIP)
if (file_exists($file))
return include($file);
return false;
}
getTemplate('news', $vars);
In your template, you can use $var1 and $var2.
you are trying to reach global variable in a function.
you must either declare a variable global in a function or just use: $GLOBALS["variable"]
function () {
global $variable;
etc..
}
Because you're including the file from inside a function, the contents of that file are no longer in the global scope.
You either need to add global $variable; to the start of the function, or use echo $GLOBALS['variable']; in news.html.
I believe your problem has to do with variable scoping. When you call a function, you are unable to access variables outside of that function, except global variables (more on this in a second) or variables passed to your function. The global function tells PHP that you'd like to use the same variable in the function as in the parent scope. You can also use the define function to define constants for your script, which are universally accessed.
Using large number of global variables is very frowned upon, I'd suggest passing either an associative array to the function, or use a more object oriented approach.
Hope this helps,
Jacob
Have you considered using Smarty
If you don't want to use this template engine maybe you should check some of the ideas behind it. In short, it deals with assigning variables to templates by assigning variable values to an object. If you assigned variable to a template object you can then use it in template file.

PHP Preserve scope when calling a function

I have a function that includes a file based on the string that gets passed to it i.e. the action variable from the query string. I use this for filtering purposes etc so people can't include files they shouldn't be able to and if the file doesn't exist a default file is loaded instead.
The problem is that when the function runs and includes the file scope, is lost because the include ran inside a function. This becomes a problem because I use a global configuration file, then I use specific configuration files for each module on the site.
The way I'm doing it at the moment is defining the variables I want to be able to use as global and then adding them into the top of the filtering function.
Is there any easier way to do this, i.e. by preserving scope when a function call is made or is there such a thing as PHP macros?
Edit: Would it be better to use extract($_GLOBALS); inside my function call instead?
Edit 2:
For anyone that cared. I realised I was over thinking the problem altogether and that instead of using a function I should just use an include, duh! That way I can keep my scope and have my cake too.
Edit: Okay, I've re-read your question and I think I get what you're talking about now:
you want something like this to work:
// myInclude.php
$x = "abc";
// -----------------------
// myRegularFile.php
function doInclude() {
include 'myInclude.php';
}
$x = "A default value";
doInclude();
echo $x; // should be "abc", but actually prints "A default value"
If you are only changing a couple of variables, and you know ahead of time which variables are going to be defined in the include, declare them as global in the doInclude() function.
Alternatively, if each of your includes could define any number of variables, you could put them all into one array:
// myInclude.php
$includedVars['x'] = "abc";
$includedVars['y'] = "def";
// ------------------
// myRegularFile.php
function doInclude() {
global $includedVars;
include 'myInclude.php';
// perhaps filter out any "unexpected" variables here if you want
}
doInclude();
extract($includedVars);
echo $x; // "abc"
echo $y; // "def"
original answer:
this sort of thing is known as "closures" and are being introduced in PHP 5.3
http://steike.com/code/php-closures/
Would it be better to use extract($_GLOBALS); inside my function call instead?
dear lord, no. if you want to access a global variable from inside a function, just use the global keyword. eg:
$x = "foo";
function wrong() {
echo $x;
}
function right() {
global $x;
echo $x;
}
wrong(); // undefined variable $x
right(); // "foo"
When it comes to configuration options (especially file paths and such) I generally just define them with absolute paths using a define(). Something like:
define('MY_CONFIG_PATH', '/home/jschmoe/myfiles/config.inc.php');
That way they're always globally accessible regardless of scope changes and unless I migrate to a different file structure it's always able to find everything.
If I understand correctly, you have a code along the lines of:
function do_include($foo) {
if (is_valid($foo))
include $foo;
}
do_include(#$_GET['foo']);
One solution (which may or may not be simple, depending on the codebase) is to move the include out in the global scope:
if (is_valid(#$_GET['foo']))
include $_GET['foo'];
Other workarounds exists (like you mentioned: declaring globals, working with the $_GLOBALS array directly, etc), but the advantage of this solution is that you don't have to remember such conventions in all the included files.
Why not return a value from your include and then set the value of the include call to a variable:
config.php
return array(
'foo'=>'bar',
'x'=>23,
'y'=>12
);
script.php
$config = require('config.php');
var_dump($config);
No need to mess up the place with global variables
Is there any easier way to do this, i.e. by preserving scope when a function call is made
You could use:
function doInclude($file, $args = array()) {
extract($args);
include($file);
}
If you don't want to explicitly pass the variables, you could call doInclude with get_defined_vars as argument, eg.:
doInclude('test.template.php', get_defined_vars());
Personally I would prefer to pass an explicit array, rather than use this, but it would work.
You can declare variables within the included file as global, ensuring they have global scope:
//inc.php
global $cfg;
$cfg['foo'] = bar;
//index.php
function get_cfg($cfgFile) {
if (valid_cfg_file($cfgFile)) {
include_once($cfgFile);
}
}
...
get_cfg('inc.php');
echo "cfg[foo]: $cfg[foo]\n";

Categories