Question from the PHP8 test

PHP code that throws an error.

Hard

What will this code display?

<?php

class Foo
{
    private ?string $bar;

    public function setBar(?string $secondLine): void
    {
        $this->bar = $secondLine;
    }

    public function getBar(): ?string
    {
        return $this->bar;
    }
}

$foo = new Foo();
echo $foo->getBar() ?? 'john doe';
Author: W3D TeamStatus: PublishedQuestion passed 951 times
Edit
6
Community Evaluations
developer avatar
Mami
12/04/2024
Moi aussi, j'ai choisi 'john doe'. Malheuresement, c'est uncaught error car on n'a pas encore initialisé la propriété $bar. Grave!
developer avatar
David
18/02/2024
pour moi ca affiche john doe...
developer avatar
Paul TOTI
06/05/2024
Si $bar n'a jamais été défini, elle est null par défaut en raison de son type nullable ( ?string). L'accÚs à une propriété nullable non initialisée qui est lue (et non écrite ou utilisée dans un contexte nécessitant une valeur non nulle) retourne simplement null. Il n'y a pas d'erreur car PHP gÚre cette situation de maniÚre interne en retournant null
developer avatar
Vincent
06/05/2024
Pas en php 8. Si on ne l'initialise pas explicitement à null, on a une erreur, alors qu'en php 7 effectivement elle était implicitement initialisée à null.