nafeeur10's avatar

Nullsafe operator

I am learning about nullsafe operator. I have written the below code:

<?php

class User 
{
    public $isoCode = '259874';

    public function getAddress() : string {
        return 'Dhaka';
    }

    public function getCountry() : string {
        return 'Bangladesh';
    }
}

$user = new User();
echo $user->getAddress()?->getCountry()?->isoCode;

But why this getAddress() giving me this error?

Fatal error: Uncaught Error: Call to a member function getCountry() on string in C:\xampp\htdocs\php8\nullsafe.php:18 Stack trace: #0 {main} thrown in C:\xampp\htdocs\php8\nullsafe.php on line 18

0 likes
5 replies
apex1's avatar

Because getAddress() is a string? How will you call getCountry() on a string?

nafeeur10's avatar

@apex1 ,

Okay. But "String" means I have a value that is not NULL. So, it should not give me error!!!!

tykus's avatar

@nafeeur10 you are getting a result that is not null, yes. However, you use an object operator -> on this result which is not valid because the result is a string.

1 like
apex1's avatar

@nafeeur10 Your code doesn't make sense. Forget about the nullsafe operator for a sec. You can't chain on getCountry() to getAddress(). You're not returning this in your methods. Look at the error: Uncaught Error: Call to a member function getCountry() on string

1 like

Please or to participate in this conversation.