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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。