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

232
Vistas
What is the benefit of readonly in PHP 8.1?

readonly is now available in PHP 8.1, I just wonder what is the use of it? Is that to help the editor to know that this property is just readonly or to help the client to know that or there is another benefit?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

readonly properties allow you to create immutable objects, or at the very least immutable properties.

That way you can be sure that a value won't be changed by accident after being initialized, throughout the object's life.

It's a very similar concept to constants (set via const or define), albeit with two important differences:

  • constants need to be defined on "compilation" time, whereas readonly properties will be set during runtime, usually during on object instantiation (so multiple instances will be able to hold different values*)
  • as opposed to constants, that live in the global scope, and in case of class constants their value is tied to the class and not to the instance.

You could achieve the same with a private property only accessible via a getter. E.g., in "the olden days":

class Foo {

    private DateTimeImmutable $createAt;

    public function __construct() {
        $this->createdAt = new DateTimeImmutable();
    }

    public getCreatedAt(): DateTimeImmutable
    {
        return $this->createdAt;
    }
}

$f = new Foo();
echo $f->getCreatedAt()->format('Y-m-d H:i:s');

The only problem with this is that it requires a lot of boilerplate code.

With PHP 8.1. the same could be achieved by doing:

class Foo
{

    public function __construct(
        public readonly DateTimeImmutable $createdAt = new DateTimeImmutable()
    )
    { }

}

$f = new Foo();
echo $f->createdAt->format('Y-m-d H:i:s')
over 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