0

My question is quite simple: In PHP OOP I want the value of an object property to be returned by a function. To be specific: I want a string to be translated with gettext. But it seems, that the value of a property has to be a string, a number or an array but not a function.

  1. Why is that so?
  2. Is there a solution for my need to have the value translated?

My code is similar to this:

<?php
class Bar extends Foo {
  public $baz = array('lorem' => __('ipsum'));

  // other code
?>
Christian
  • 325
  • 2
  • 10
  • 3
    properties must be scalar. – Ryan Oct 25 '14 at 01:14
  • Properties are set at compile-time (when the code is being read and parsed). Code that calls stuff like methods and functions is run at run-time (when the code is running). So, no, it is not possible to call a function like this. I believe there are plans to make simple expressions (such as addition and string concatenation) possible at compile-time in the future, but calling functions at compile-time will most likely never be possible. – Sverri M. Olsen Oct 25 '14 at 01:20

2 Answers2

2

If you look at the manual regarding properties, you will see that:

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.

So you cannot use a function when you declare the property.

However, the value can be set somewhere else, so in your case you could set it for example in the constructor:

<?php
class Bar extends Foo {
  public $baz;

  function __construct()
  {
     $this->baz = array('lorem' => __('ipsum'));
  }

  // other code
?>
jeroen
  • 91,079
  • 21
  • 114
  • 132
0

Properties in PHP for classes must be a scalar value, therefore, you cannot expect to call a function as the property value. To properly to do this, you would need to set the value in the constructor.

<?php
class Bar extends Foo {
  public $baz = array('lorem' => NULL);

  public function __construct() 
  {
    $this->baz['lorem'] = __('ipsum')
  }
?>
Ryan
  • 14,392
  • 8
  • 62
  • 102
  • 1
    "Scalar" is not the right word. Arrays are not scalar, for instance. The right word would be "constant value" (i.e. a value that does not depend on run-time information). – Sverri M. Olsen Oct 25 '14 at 01:26