strange controller method/property error

I’m working through a classic “Hello World!” tutorial, and here’s my problem:

One exercise had me altering the relevant controller action (originally containing simply:

public function actionHelloWorld()





public function actionHelloWorld()


$theTime = date("D M j G:i:s T Y");



The attribute $time is then available for me to echo out in my view. No problems there. I was then encouraged to, on my own, create a public class property for the current time in the controller which would then be accessible in the view via $this-> …

Seemed straightforward to me, but whenever I tried the following code "public $time = date("D M j G:i:s T Y");" in my controller class I get the following error before I ever get a chance to call anything from within the view:

“Parse error: syntax error, unexpected ‘(’, expecting ‘,’ or ‘;’ in C:\wamp\www\demo\protected\controllers\MessageController.php on line 6”

(line 6 being the line containing the above property code.)

The strange thing, is that if I put that code into a method, e.g.:

public function currentTime() {

return $theTime = date("D M j G:i:s T Y");


and then call it in my view via "<?php echo $this->currentTime(); ?>" then everything works fine. What in the world am I missing?

You can only assign primitive (int, string, bool etc) types to member variables by default. To assign the date, put it in the controller’s init method e.g.

public function init()


    $this->time = date('jS F Y, g:ia');



public $time = date("D M j G:i:s T Y");

You line 6 in MessageController? If it is then im not sure if you can call date in there.

public $time = date("D M j G:i:s T Y")

This is a PHP issue - class member variables can only have constant assignments, such as "foo" or null or 123. Calling a function is not allowed.

If you just want the current time, do

public function getCurrentTime() {

    return date("D M j G:i:s T Y");


… and then use it as

echo $this->currentTime;

Awesome. Thanks all for great/quick responses (and for the subtle example of how I could have simplified my code a bit ;)

One thing more, why exactly are you not able to call a function when defining a class variable/property?

… because PHP says so - it’s just how the language was designed.