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?

Mr. Bug
  • 57
  • 5
  • 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](http://php.net/manual/en/language.variables.scope.php). – FirstOne Jul 31 '16 at 14:14

1 Answers1

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];
    }
}
Community
  • 1
  • 1
Machavity
  • 30,841
  • 27
  • 92
  • 100
  • 1
    @FirstOne Per the OP, `$lang` is defined in the `trans_mig.php` include, which is in the constructor – Machavity Jul 31 '16 at 14:20
  • Yes, now working great, I didn't image that this practice could work. Thanks :) – Mr. Bug Jul 31 '16 at 14:20
  • 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) – rjdown Jul 31 '16 at 14:22
  • 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 – FirstOne Jul 31 '16 at 14:22