我正在构建一个简单的多语言系统。我创建了一个名为Language的类,该类由控制器加载,该类非常简单:
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];
}
}
里面的trans_mig.php
我有以下内容:
$lang['home'] = 'Home';
$lang['user'] = 'User';
但是当我这样做时:
$this->lang->line('user');
我收到以下错误:
注意:未定义的变量:lang
在我包含的文件中,我在trans_mig.php
做什么错?
public function line($key)
{
return $lang[$key];
}
您不是$lang
在函数中定义。因此,由于变量作用域,它没有在您的函数中定义。
您应该做的是$lang
在类中定义并从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];
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句