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

350
Visualizações
Using '<' to compare two objects in PHP

My friend asked me how can she create and compare dates in PHP. Since I knew that there is a DateTime class in PHP I told her to search about it and use it once understood, however I was not sure about the comparison stuff. So I googled how could you compare dates in PHP. I thought the DateTime class uses some inbuilt method to compare dates. But to my surprise, the code looked something like this:

$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);

if ($expire_dt < $today_dt) { /* Do something */ }

What I don't understand is how can a comparison operator like < be used to compare two 'Objects'. I thought you could only compare primitive datatypes using the comparison operators. So how does PHP compare two 'Objects' using the comparison operators?

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

0

It is not well documented, but when comparing objects, PHP compares member variables one by one in order of declaration, until it finds the first uneven variable, and returns a result based on that.

more details here: http://us3.php.net/manual/en/language.oop5.object-comparison.php#98725

about 4 years ago · Santiago Trujillo Relatório

0

Yes, usually, you would be correct -> but, for PHP's inbuilt classes, such as DateTime, this is different. https://wiki.php.net/internals/engine/objects#compare_objects.

I wish there was an implementation for a "__compare" magic method to implement comparison. However, for now, you have 2 options:

Edit after reading answer of @WhatHaveYouTriedSoFar above: 1) you could make use of the way PHP compares objects, "the comparison operation stops and returns at the first unequal property found" (http://us3.php.net/manual/en/language.oop5.object-comparison.php#98725)

2) you could create your own "compare" method.

about 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