Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
A confusion about time() function in PHP

I cannot understand why the result of subtracting the current time from the variable of $_session['now'] that has included the previous time is zero.


I expected outputting the difference between the current time and the time when i have created the variable $student->now. Explain me please.

class Student
{

    public function __set($key, $value)
    {
        $_SESSION[$key] = $value ;
    }


    public function __get($key)
    {
        return $_SESSION[$key];

    }

}
session_start();

$student = new Student() ;

//__set function will be called ;
$student->now = time();


//__get function will be called ;
echo time() - $_SESSION["now"]; // output is zero ?!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

time() has a precision of ONE second, you are basically doing:


$now = time(); // e.g. 1627385278

echo time() - $now; // 1627385278 - 1627385278

This happens very fast, so the output is (almost always) zero.

The fact that your example code involves a "session" hints that you want to measure time between different HTTP requests. If that is the case, some logic is needed to ONLY set the stored value for the first time, but not thereafter.

over 4 years ago · Santiago Trujillo Relatório

0

The $_session['now'] variable is set in the line before the echo. In the echo line the current time is compared to the time set in the line before.

Because both lines are executed directly after each other, both are executed within the same second. There will be a difference of milliseconds but time() function is measured in seconds, refer to: https://www.php.net/manual/en/function.time.php.

That's why both timestamps are the same and there is no difference between these when comparing them.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda