douao1858 2015-03-16 06:25
浏览 29
已采纳

PHP使用本地化字符串值声明数组

experts!

This is surely a newbie issue, but I am stuck with my project. Problem is this: an array of objects is declared and these objects should have a value when array is declared. Code works ok if values are given in string format, e.g. 'foo bar'. However same array declaration gives me an error if value is set by an function.

Here's the code...

Works ok:

private static $summary_fields = array(
        'Title' => 'Title',
        'Description' => 'Description',
        'SummaryOfPrice' => 'Amount',
        'Country.Title' => 'Country'
    );

Works NOT ok:

private static $summary_fields = array(
        'Title' => _t('FlatFeeShippingRate.DESCRIPTION', 'Title'),
        'Description' => _t('FlatFeeShippingRate.DESCRIPTION', 'Description'),
        'SummaryOfPrice' => _t('FlatFeeShippingRate.AMOUNT', 'Amount'),
        'Country.Title' => _t('FlatFeeShippingRate.COUNTRY', 'Country')
    );

Function _t() here is the function that localizes the string. If localized string is not found from .yml-language specific file, it returns the string that is given as the second parameter.

What is wrong with the array declaration when _t() produces an error :

Parse error: syntax error, unexpected '(', expecting ')'

Other places used _t()-function works as charm!

Please help.

Thx!

  • 写回答

1条回答 默认 最新

  • dongwai4434 2015-03-16 07:41
    关注

    From http://us.php.net/manual/en/language.oop5.static.php:

    Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

    This means that you cannot use the _t() function within the initializer. However, you can create a getter function, as suggested here. You can also initialize the array after you create the class, suggested here.

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

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等