Stoic
Stoic

Reputation: 10754

Initialize a Class variable with date function?

I am trying to do this:

class A {
 public $var1 = date('U');
}

But, obviously, above is failing due to Syntax Error.

Can someone let me know of an alternate way of doing this.

I have around 100s of such dateTime variable and hence, using a constructor is not really what can be beneficial, however, I am still waiting for anyway possible to do this.

Upvotes: 2

Views: 3278

Answers (2)

Seph
Seph

Reputation: 1094

Jacob's answer is not entirely correct.

Put simply, you cannot make function calls from within a class and outside of a function.

This

class A {
   public static $var1 = date('c');
}

Will not work as you are still making a call to date()

But if you must, then

class A {
   public static $var1;
        public function __construct()
    {
        static::$var1 = date("c");
    }
}

Use self or static to instantiate your variable within the class constructor. Both do different things.

Upvotes: 4

Jacob Relkin
Jacob Relkin

Reputation: 163288

Make it static if you truly want it to be a class variable:

class A {
   public static $var1 = date('U');
}

Or, if you want it to be an instance variable:

class A {
   public $var1;
   function __construct() {
      $this->var1 = date('U');
   }
}

Upvotes: 5

Related Questions