我在包含文件中访问数组时遇到问题。代码仅在我直接包含en.php时才有效。 Mayby我无法访问数组单词,因为en.php是" sub-included"?
的index.php
<?php
include 'localization/langSwitcher.php';
echo $words['title'];
langSwitcher.php
<?php
function SetLanguage()
{
if(isset($_COOKIE['lang']))
{
switch ($_COOKIE['lang']) {
case 'en':
include 'localization/en.php';
break;
default:
include 'localization/en.php';
setcookie('lang', 'en', time() + 365 * 24 * 3600, '/');
break;
}
}
else
setcookie('lang', 'en', time() + 365 * 24 * 3600, '/');
}
SetLanguage();
en.php
<?php
$words = array(
'title' => 'Welcome on Trex where you can buy or sell via Internet!',
'' => ''
);
答案 0 :(得分:2)
作为函数中包含的文件 - 此函数中的所有变量在函数外部都不可用。
因此,您应该使用global
关键字,例如:
$words = array();
function SetLanguage()
{
global $words; // here
if(isset($_COOKIE['lang']))
{
switch ($_COOKIE['lang']) {
case 'en':
include 'localization/en.php';
break;
default:
include 'localization/en.php';
setcookie('lang', 'en', time() + 365 * 24 * 3600, '/');
break;
}
}
else
setcookie('lang', 'en', time() + 365 * 24 * 3600, '/');
}
SetLanguage();
或者你的函数可以返回$words
执行结果。