-1

So I have made a custom function that will search in a set location for the file and return it. I include the helper that contains this function and then include a file with variables.

I want to then be able to access these variables in the included files using the function.

Here is my setup:

Main file

<?php

require 'helper.php';

require 'variable.php';

$Helper -> include_asset("text.php");

?>

Helper.php

<?php 

function include_asset($file) {

    $full_path = "path/to/assets/folder/".$file;

    return (file_exists($full_path)) ? include $full_path : "file ".$file." does not exist";
}

?>

variable.php

<?php $text = "hello"; ?>

text.php

<?php echo $text; ?>

Problem is that the variable $text can not be accessed within the included file but can within the main file. I think it has something to do with the include custom function being a function so variable scope but not sure. Any help?

user3683675
  • 125
  • 10
  • You need to either, not use a function to include the file. Or use globals: http://php.net/manual/en/reserved.variables.globals.php – Antony Thompson Dec 22 '16 at 01:01

1 Answers1

0

Since you're including the file inside a function, any variables it creates are local to the function by default. You can use a global declaration to make them global:

variable.php:

<?php
global $text;
$text = "hello";
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I thought this maybe the reason. Would it be possible to throw an array of variables into the $Helper -> include_asset("text.php"); and then make them accessible? – user3683675 Dec 22 '16 at 19:16
  • I'm not sure what you mean by that. The way you call the functions is irrelevant, all that matters is that you're doing the include inside a function, that makes the variables local. – Barmar Dec 22 '16 at 19:17
  • $Helper -> include_asset("text.php", $array); and the $array being an array of variables that the function can then access. That way the variables are within the scope of the include function – user3683675 Dec 22 '16 at 19:30
  • You can do that in PHP 5, because you can write `global $$variable;` to dynamically declare variables global. But PHP 7 has removed this, so you shouldn't write code like that. – Barmar Dec 22 '16 at 19:33