Good morning,
I am trying to to learn how the file inclusion in php works. Today, I am having a problem that I can not solve. This is my scenario:
Files at same directory:
- config.php
- db.php
- functions.php
- form.php
config.php
<?php
$config['json_file'] = 'test.json';
functions.php
<?php
function writeInFile()
{
echo $config['json_file']; // just for debugging porpuses
file_put_contents($config['json_file'], json_encode(time()));
}
model.php
<?php
class Model{
public function __construct();
function create()
{
writeInFile();
}
}
form.php
<?php
include('config.php');
include('functions.php');
include('model.php');
$model = new \Model();
$m->create();
When I execute the form.php
I get this error:
Warning: file_put_contents() [function.file-put-contents]: Filename cannot be empty in functions.php
I know that this happens because the var $config['json_file']
is null inside of writeInFile()
in functions.php. But, theorically it should works because I am doing the inclusion at the begginig of form.php. Or am I wrong?
Read variable scope from here [variable scope][1]
[1]: http://php.net/manual/en/language.variables.scope.php .
Right at the begining it sais that a function from another file that was included can't use a variable from another file beause it is considered to be in local scope . That's why you get error . Read more about var scope .