1

I don't really know what to google, as I have kind of picked up PHP and OOP without knowing the jargon.

Why doesn't this work in PHP?

class Calendar{
    public $derp="lala";
    public $todaysDate=date('Y-m-d',strtotime('2013-04-11'));
}

But this does?

class Calendar{
    public $derp="lala";
    public function __construct() 
    {
        $this->todaysDate=date('Y-m-d',strtotime('2013-04-11'));
    }
}

You can't declare a date at the beginning of a class? Why?

Nick Manning
  • 2,828
  • 1
  • 29
  • 50
  • * [Attribute declarations in a class definition can only be constant values, not expressions.](http://stackoverflow.com/questions/2671928/workaround-for-basic-syntax-not-being-parsed) – mario Apr 11 '13 at 23:50

2 Answers2

3

From PHP.net

TL;DR You cannot initialize properties with non constant values. Functions are not constant values.

Properties

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable
declaration. 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.

Marcos
  • 4,643
  • 7
  • 33
  • 60
0

date is a function. Functions are called from methods. Plus giving your $todaysDate variable a value is more appropriate in the constructor.

christopher
  • 26,815
  • 5
  • 55
  • 89