0

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?

manix
  • 14,537
  • 11
  • 70
  • 107
  • 2
    I think you need to pass a parameter to `writeInFile()` – pulsar Jul 23 '13 at 15:59
  • I do not think so. It is because file_put_contents need a filename to write, it because the config var arrives as null at this function – manix Jul 23 '13 at 16:06
  • 2
    @manix - You can either pass `$config` into the function as a parameter; or you can declare it as a global variable. Otherwise, it's out of scope. That's why you're seeing the null value - `$config` is out of scope. – andrewsi Jul 23 '13 at 16:10
  • In this case, what is the scope of config.php? – manix Jul 23 '13 at 16:12
  • 1
    @manix - when you include a file, it's effectively the same as cutting and pasting the contents of the included file. So any variables you've defined in config.php will have the same scope as `$model`. – andrewsi Jul 23 '13 at 16:16

1 Answers1

1

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 .

Geo C.
  • 755
  • 6
  • 18