Mr. Bug
Mr. Bug

Reputation: 57

Cannot get variable of another php file

I'm building a simple multi-languages system. I've created a class called Language that is loaded by my controller, the class is very simple:

class Language
{
    private $_langPath = null;

    function __construct()
    {
        $this->_langPath = 'languages/' . LANGUAGES . '/trans_mig.php';

        if(!file_exists($this->_langPath))
        {
           throw new exception("File not found: " . LANG);
        }
        else
        {
           include $this->_langPath;
        } 
    }

    public function line($key)
    {
        return $lang[$key];
    }
}

inside the trans_mig.php I've the following:

$lang['home'] = 'Home';
$lang['user'] = 'User';

but when I do for example this:

$this->lang->line('user');

I get the following error:

Notice: Undefined variable: lang

in the file that I've included the trans_mig.php, what am I doing wrong?

Upvotes: 1

Views: 60

Answers (1)

Machavity
Machavity

Reputation: 31644

public function line($key)
{
    return $lang[$key];
}

You're not defining $lang within the function. So, due to variable scope, it's not defined within your function.

What you should do is define $lang within your class and pull the variable from your include

class Language
{
    private $_langPath = null;
    /** @var array */
    protected $lang;

    function __construct()
    {
        $this->_langPath = 'languages/' . LANGUAGES . '/trans_mig.php';

        if(!file_exists($this->_langPath))
        {
           throw new exception("File not found: " . LANG);
        }
        else
        {
           include $this->_langPath;
        } 
        $this->lang = $lang;
    }

    public function line($key)
    {
        return $this->lang[$key];
    }
}

Upvotes: 2

Related Questions