Reputation: 5612
I have file:
en.php
<?php
$lang['word'] = 'word';
$lang['text'] = 'text';
index.php
<?php
function load($file) {
include $file . '.php';
echo $lang['word'];
echo $lang['text'];
}
load('en');
How to get array values from en.php and return them as array with load().
How to process file to return each array value in load() to use it in index.php like this:
echo $lang['word'];
I know that include function view file in global scope but variables are in local scope. There for I am looking in "return as array" solution.
Edit:
I want to separate languagse in files en.php, de.php, ru.php ... and then load them into index.php with load. Then retrieve them and echo as $lang['text']
.
Upvotes: 0
Views: 1894
Reputation: 158
Ing. Michal Hudak
Your code is correct
<?php
function load($file) {
include $file . '.php';
return $lang;
}
print_r(load('en'));
Upvotes: 2
Reputation: 780724
You can use the global
declaration to make $lang
a global variable:
function load($file) {
global $lang;
include $file . '.php';
echo $lang['word'];
echo $lang['text'];
}
Upvotes: 0
Reputation: 3329
you are including the file en.php inside the function so $lang
is local for the function and you can use them directly.
function load($file) {
include $file . '.php';
echo $lang['word'];
echo $lang['text'];
}
If you include the file outside the function then $lang
will be global
for the function and you can access this by using global keyword.
like:
include 'en.php';
function load() {
global $lang;
echo '<br>'.$lang['word'];
echo '<br>'.$lang['text'];
}
Upvotes: 0
Reputation: 3582
en.php (or lang_en.php)
<?php
class lang_en {
var $lang = array();
public function __construct() {
$this->lang['word'] = 'word';
$this->lang['text'] = 'text';
}
public function get_lang() {
return $this->lang;
}
}
?>
index.php
<?php
function load($file) {
include $file . '.php';
$class_name = 'lang_' . $file;
$lang_instance = new $class_name();
$get_lang = $lang_instance->get_lang();
echo $get_lang['word'];
echo $get_lang['text'];
}
load('en');
?>
Untested & it's early - but this should work...
Upvotes: 0
Reputation: 4391
you can simply do a return $lang
in your en.php file and then assign it to a variable in the load function: $load = include $file . '.php';
Upvotes: 1