Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

346
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda