1

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!

nybondasto
  • 13
  • 2
  • 1
    no, you can't use your functions on initialization on properties. quoting the manual http://php.net/manual/en/language.oop5.properties.php _This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated._ – Kevin Mar 16 '15 at 06:29
  • Hi, ghost! Okay... er.. how should I change that to be valid initialization? – nybondasto Mar 16 '15 at 07:07
  • set it inside the constructor – Kevin Mar 16 '15 at 07:37
  • Ghost, thanks for your help! :) I couldn't mark this as an accepted answer, because you added this as an comment... sorry. But your answer was the first helpful one, thanks! – nybondasto Mar 16 '15 at 07:58
  • no problem im glad this shed some light – Kevin Mar 16 '15 at 10:09

1 Answers1

0

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.

Community
  • 1
  • 1
WillS
  • 362
  • 1
  • 12