Reputation: 692
I have a file 'config.php' which Is included at the beginning of my program (see below)
Main file runs require 'config.php';
config.php
<?
global $config;
$config['tblist'] = 'pending';
$config['tbdone'] = 'checked';
$config['checkfreq'] = 24;
?>
I then create a new page object
$page = new Page($name,$source);
One of the functions in that page object I want to be able to grab stuff from the config but it doesn't seem to be able to reference to $config. Have I put global $config; in the right place?
Upvotes: 2
Views: 11746
Reputation: 20431
When making references to global variables in functions, you must declare them as global:
global $config;
This is also interesting: http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/
There is no way to declare a variable. Variables that don’t exist are created with a null value when first used.
Global variables need a global declaration before they can be used. This is a natural consequence of the above, so it would be perfectly reasonable, except that globals can’t even be read without an explicit declaration—PHP will quietly create a local with the same name, instead. I’m not aware of another language with similar scoping issues.
To be fair it will also throw a Notice if you've got them enabled.
Upvotes: 5
Reputation: 1309
You can include $config from within your Page object:
class Page
{
protected $config;
public function __construct($configPath)
{
include $configPath;
$this->config=$config;
}
}
Upvotes: 0
Reputation: 141
In the function that needs to use $config, did you first declare $config as global? For example:
function foo() {
global $config;
$a = $config['tblist'];
....
}
$config will only refer to the global variable if first declared as such, if not it will refer to a variable in the local scope.
You can find more details on globals here: PHP Globals
Upvotes: 2
Reputation: 3386
Put global $config
inside the function before using the variable.
See the PHP manual on variable scope for examples.
Upvotes: 2
Reputation: 342
You should in function declare $config is global variable
Maybe you need PHP variable scope
Upvotes: 0