0

I get an error when I use date() when initializing an instance variable

class User extends Connectable {
    private $date = date('Y-m-d');
}

The error is

 Parse error: syntax error, unexpected '(', expecting ',' or ';' 

This is weird, because it works fine when I call date() from inside a function, or outside the class...

George Newton
  • 3,033
  • 7
  • 30
  • 46

4 Answers4

2

The properties 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.

You could initialize it in the constructor method.

xdazz
  • 154,648
  • 35
  • 237
  • 264
1

You should do that under a constructor

<?php
class User extends Connectable {
    private $date;
    function __construct()
    {
    $this->date = date('Y-m-d');
    }
}
Shankar Narayana Damodaran
  • 66,874
  • 43
  • 94
  • 124
1

Such expressions are not allowed as a field default value. You need to set them in the constructor.

Realitätsverlust
  • 3,913
  • 2
  • 21
  • 45
1

try this you can use a constructor for it which initialize your private variable when the object is created.

class User extends Connectable {
    private $date1; 

    function __construct()
     {
       $this->date1 = date('Y-m-d');
     }
}
Satish Sharma
  • 9,475
  • 6
  • 27
  • 51