dongzhi7763 2017-05-13 08:09
浏览 25
已采纳

PHP问题的翻译

I am using a translator class i found online. It works phenomenally when I use it to directly echo the message. The problem occurs when I do conditional checks at the beginning of the page and I need to have the translated text in the variable to then send it to other places on the page to be displayed.

My code:

if ($condition_1){
    $message = $translate->__('Text 1');
}

elseif ($condition_2){
    $message = $translate->__('Text 2');
}

elseif ($condition_3){
    $message = $translate->__('Text 3');
}

This code echos the text in the place where this condition is put, not used as the variable $message and then echos when I need it to. Can you help me to figure out how to use the text as a variable.

If I use the text with no translator class. I can easily use it as a variable.

This is the class i use:

class Translator {

    private $language   = 'sl';
    private $lang       = array();

    public function __construct($language){
        $this->language = $language;
    }

    private function findString($str) {
        if (array_key_exists($str, $this->lang[$this->language])) {
            echo $this->lang[$this->language][$str];
            return;
        }
        echo $str;
    }

    private function splitStrings($str) {
        return explode('=',trim($str));
    }

    public function __($str) {  
        if (!array_key_exists($this->language, $this->lang)) {
            if (file_exists($this->language.'.txt')) {
                $strings = array_map(array($this,'splitStrings'),file($this->language.'.txt'));
                foreach ($strings as $k => $v) {
                    $this->lang[$this->language][$v[0]] = $v[1];
                }
                return $this->findString($str);
            }
            else {
                echo $str;
            }
        }
        else {
            return $this->findString($str);
        }
    }
}

The translated text is in the a *.txt file, looking like this:

text 1=text 1 translated
text 2=text 2 translated
text 3=text 3 translated
  • 写回答

1条回答 默认 最新

  • dongzhaoshi8497 2017-05-13 08:33
    关注

    The problem was in the "echo" in the class. I changed the "echo" with "return" and it works like a charm!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)