Monday, 7 October 2019

php - Why can't I declare a "date" in a class?




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?


Answer



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.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...