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,153
  • 7
  • 34
  • 49

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
  • 158,678
  • 38
  • 247
  • 274
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
  • 68,075
  • 43
  • 96
  • 126
1

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

Realitätsverlust
  • 3,941
  • 2
  • 22
  • 46
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,547
  • 6
  • 29
  • 51