1

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?

1
  • 1
    $lang is defined outside of the class. There is no $lang property in the Language class, so you can't access it with $this. Variable scope. Commented Jul 31, 2016 at 14:14

1 Answer 1

2
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];
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

@FirstOne Per the OP, $lang is defined in the trans_mig.php include, which is in the constructor
Yes, now working great, I didn't image that this practice could work. Thanks :)
Another option, in your include, you can add return $lang; at the end, then you could do $this->lang = include $this->_langPath; while avoiding variable pollution (sometimes this can be an issue)
Ohhhhhhh.. include $this->_langPath; brain lag xD ..I guess I was looking for include() hehe.. mb - I'll just remove my previous comment.. that was so off lol

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.