skip to Main Content

I’m having trouble understanding the behavior of php in a class with a typed variable, when I try to access the method even if it is null I get an error

enter image description here

enter image description here

<?php

class City
{
    private string $id;
    private string $name;

    public function getId(): ?string
    {
        return $this->id;
    }

    public function setId(string $id): City
    {
        $this->id = $id;
        return $this;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): City
    {
        $this->name = $name;
        return $this;
    }
}

$city = new City();
$x = $city->getName();

I expected the same behavior as php whether or not the variable is typed

3

Answers


  1. When a type is declared, all properties will have an uninitialized state. It is not allowed to access class properties prior to assigning an explicit value.

    You can check if a class property is uninitialized using isset($foo->name). Because this value is not the same as null, You cannot use $foo->name === null to check if the property is uninitialized.

     var_dump($foo->name === null);
    

    In the above Code, If the $name property is uninitialized, This will throw an error:

    Error: Typed property Example::$name must not be accessed before initialization in..
    
    Login or Signup to reply.
  2. If you give a class property a type that isn’t nullable and provide no default value, you’ll receive an error if the property’s value is accessed before being set.

    You would need to change to:

    private ?string $id = null;
    private ?string $name = null;
    
    Login or Signup to reply.
  3. In PHP, when you have a typed property (as of PHP 7.4) or a typed return type in a method, attempting to access that property or call that method on an instance with a null value can lead to a fatal error. PHP’s type system is strict, and it enforces type safety. If you specify a type for a property or method, PHP expects that the value will conform to that type. If it doesn’t, it raises an error.

    we have a City class with a private property $name, which is initialized in the constructor. The getName() method is expected to return a string. When we create an instance of the City class with a valid name and then call getName(), it should work correctly.

    class City {
      private string $name;
    
      public
      function __construct(string $name) {
        $this - > name = $name;
      }
    
      public
      function getName(): string {
        return $this - > name;
      }
    }
    
    $city = new City("New York");
    
    $x = $city - > getName();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search