【问题标题】:PHP echo gettext from a classPHP从一个类中回显gettext
【发布时间】:2021-06-29 13:26:52
【问题描述】:

我对类有点陌生,并尝试从方法返回一个数组和一个 gettext 字符串,因此我可以稍后验证该数组并回显该字符串。 由于我缺乏知识,我认为这更像是一个语法问题 - 但我无法弄清楚如何使用非法偏移字符串来避免该警告。简化的代码如下。希望有人能帮忙?

class.php

class test {
  private $a = 1;
  public function validate() {
    
    if($this->a == 1) {
        //return _("SUCCESS"); <-this works fine
        
        //I would like to return array AND gettext message together
        //something like this I tried:        
        return array('status'=>1, 'message'=>_("SUCCESS"));
    }
}
$test = new test();

index.php

  $message = $test->validate();

 //echo $message; <-this works fine

 //But when I try this, I get Illegal offset string Warning...
 echo $message['status']; 

【问题讨论】:

  • var_dump($message) 在调用 validate 后确保它包含您认为的内容。
  • "echo $message; &lt;-this works fine" 打印出Array?
  • $test = new test(); 应该在 index.php 中,而不是在 class.php 中。
  • 谢谢你们,var_dump 包含我搜索的值。并移动 $test = new test();到 index.php 完全解决了它。但是为什么我不能把它放在class.php中,只是我很好奇。
  • 我想你可以把它留在类脚本中。但这没有任何意义。你系统的流程在索引脚本中,类脚本应该作为库工作,不参与主流程。

标签: php class methods gettext


【解决方案1】:

class.php

class test {
    private $a = 1;
    public function validate()
    {
        if($this->a == 1)
            return array('status'=>1);
    }
}

index.php

include('class.php');
$test = new test();
$message = $test->validate();
echo $message['status'];

【讨论】:

  • 感谢您的回答,但这只会返回状态数组。问题在上面解决了,我不得不把 $test = new test();进入 index.php,而不是 class.php
  • 是的,我同意你的看法。这是正确的方法。现在说得通了!
猜你喜欢
  • 1970-01-01
  • 2017-05-06
  • 2012-12-16
  • 2013-11-02
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
相关资源
最近更新 更多