Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use PHP time() function in a class

Tags:

php

time

This is surely a very easy question, but I can't seem to find an answer anywhere. I am writing a PHP class that needs to know what the current time is.

This code works:

class className{
    private $currentTime = 1475607467;
[...]
}

This code does not:

class className{
    private $currentTime = time();
[...]
}

What gives? Since "time()" is returning the same 10-digit number, shouldn't these be equivalent?

like image 966
Mr.Tweedy Avatar asked Sep 17 '26 07:09

Mr.Tweedy


2 Answers

I suggest you populate that property in the constructor:

class className
{

    private $currentTime;

    public function __construct()
    {
        $this->currentTime = time();
    }

    [...]
}

Take your time and read carefully this section of PHP documentation on class properties. This will save a lot of time for you in the future.

like image 55
Georgy Ivanov Avatar answered Sep 18 '26 21:09

Georgy Ivanov


As mario already pointed out, you cannot declare a property using an expression. So you can use the construct function to initialize the class properties:

class className{

    private $currentTime;

    public function __construct()
    {
        $this->currentTime = time();
    }
    [...]
}
like image 24
Sharlike Avatar answered Sep 18 '26 19:09

Sharlike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!