Domanda

Inside a class I have 2 associative arrays. I am trying to call elements from one array to be used in another (kind of master) array.

I would like to ask whether the following can be done, or can't, or what I'm doing so wrong;

Please note, the arrays are examples.

class ProductData {

    private $texture = [0=>'Cream', 1=>'Powder', 2=>'Liquid', 3=>'Paste', 4=>'Solid'];

    private $food = ['type'=>'Pasta', 'info'=>[1=>'750gm', 2=>'$4.50', 3=>$this->texture[4]],
                     'type'=>'Soup', 'info'=>[1=>'500ml', 2=>'$7.60', 3=>$this->texture[2]]];

    // Constructor, Function(s) to access the $food array...
}

Well I have found out the hard way that this cannot be done. I receive a syntax error;

  • syntax error unexpected '$this' (T_VARIABLE).

If I replace the $this with $texture, I receive the same error;

  • syntax error unexpected '$texture' (T_VARIABLE).

I'm thinking that this cannot be done, or I'm doing something very wrong, or both.

If this can be done, any assistance is very much appreciated.

Thanks, njc

È stato utile?

Soluzione

class ProductData {

private $texture;
private $food;

function __construct(){

    $this->texture = [0=>'Cream', 1=>'Powder', 2=>'Liquid', 3=>'Paste', 4=>'Solid'];
    $this->food = ['type'=>'Pasta', 'info'=>[1=>'750gm', 2=>'$4.50', 3=>$this->texture[4]],
                 'type'=>'Soup', 'info'=>[1=>'500ml', 2=>'$7.60', 3=>$this->texture[2]]];
     //other construct stuff

}

}

Altri suggerimenti

You can only use constant values to define property values outside class methods. So in your case, you cannot use the $this variable, as it references the current object instance.

You should move the initialisation to the __construct (which is really what is meant to be for)

Check out the documentation:

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top