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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大