0

I have problems with accessing array in included file. Code works only when I directly include en.php. Mayby I cannot access to array words because en.php is "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!', 
    '' => ''
);
saksija
  • 3
  • 4
  • 1
    It'll be a scope issue. You're setting up `$words` inside a function, and it's not accessible from outside that function - you'll have to either use a global, or return `$words` from your function instead – andrewsi Oct 31 '15 at 14:34

1 Answers1

2

As file included within a function - all variables in this function are not available outside function.

So you should use global keyword for example:

$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();

Or your function can return $words a result of it's execution.

u_mulder
  • 54,101
  • 5
  • 48
  • 64