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?
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.
Put global $config inside the function before using the variable.
See the PHP manual on variable scope for examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With