0

Can someone please explain me why the following doesn't work, or give me a link which explains why? I can't find it here or on google.

This works:

var_dump( array( 'test' => rand(1,5) ) );

This does not:

$myClass = new myClass();
var_dump($myClass->array);

class myClass {

    public $array = array( 'test' => rand(1,5) );

}

It doesn't like the function call in the array:

Parse error: syntax error, unexpected '(', expecting ')'

I guess it is my lack of understanding. If someone could help me to understand it, this would be nice.

Thanks!

bouteillebleu
  • 2,456
  • 23
  • 32
Talisin
  • 614
  • 1
  • 6
  • 17
  • It does not look me a duplicate one. – Shakti Singh Nov 30 '11 at 09:30
  • u can`t write it in a class properties – Dezigo Nov 30 '11 at 09:34
  • 1
    @ShaktiSingh OP is asking to initialize a property with a computed value, e.g. depends on runtime information. That's the same problem as in the linked duplicate. And it doesnt work for the same reason that's cited in the accepted answer. – Gordon Nov 30 '11 at 09:43

1 Answers1

2
$myClass = new myClass();
var_dump($myClass->array);

class myClass {

    public $array;

    function myClass(){
        $this -> array =  array( 'test' => rand(1,5) );
    }

}   

For more details: What is the better approach to initialize class variables?

Community
  • 1
  • 1
Riz
  • 9,703
  • 8
  • 38
  • 54