I have a file named “config.php” which contains a variable named $unit_names. In a class I have the following method which returns unit name by it’s id. I use this method for all rows in a table, but the problem is config.php is included only in the first call to the method. next calls cause the notice: undefined variable $unit_names...
If I replace include_once by include the notice disappears. But why? include_once should load the config.php file.
public function get_unit_name($unit_id)
{
include_once("config.php");
return $unit_names[$unit_id];
}
include_oncewill not load the specified file at least once, it will load it exactly once! If you call the function the second time, the file has already been included and will therefore not be included again, hence the error message.The idea with this is that you use
include_once/require_oncewhen you include files that contain function or class definitions, i.e., files that would produce an error if they were loaded more than once. If it’s okay to load a file twice or more times, always useinclude()instead ofinclude_once().Consider something like this instead (to save the cost of re-including the file every time):