PHP 7 type greeting

There are many questions about the hint of the return type of PHP 7 and why it is impossible to return null if the class was defined as the return type. Like this one: The right way to handle PHP 7 return types . Answers usually say that this is not a problem, since a function should return a class and then return zero, which is probably the exception. Maybe I missed something, but I really don't understand why. For example, consider a simple user class:

class User
{
    private $username;  // mandatory
    private $password;  // mandatory
    private $realName;  // optional
    private $address;   // optional

    public function getUsername() : string {
        return $this->username;
    }

    public function setUsername(string $username) {
        $this->username = $username;
    }

    public function getPassword() : string {
        return $this->password;
    }

    public function setPassword(string $password) {
        $this->password = $password;
    }

    public function getRealName() : string {
        return $this->realName;
    }

    public function setRealName(string $realName = null) {
        $this->realName = $realName;
    }

    public function getAddress() : Address {
        return $this->address;
    }

    public function setAddress(Address $address = null) {
        $this->address = $address;
    }

}

realName / . realName address null - . , ().

. 100 PHP, . catch try null .

, ?

+4
2

, .

-, , . . .

null is evil ( ), . (null ), . , "" ( , ), . , , .

( - ):

1)

$user->getProfileData() {
    return [
        'username': $this->username,
        'realName': $this->realName ? $this->realName : '',
        'address': $this->address ? $this->address : 'Not specified'
        ...
    ];
}

, (). (, ), , .

( " " ) " ". - .

, , "" , ( ).

2)

$user->showProfile($profileView) {
    $profileView->addLabel('First Name');
    $profileView->addString($this->username);
    ...
}

, , - , SRP.

3) ,

$userPresentation = $user->createPresentation()
// internally it will return new UserPresentation($this->username, this->realName, $this->address, ...);
// now display it - generate the template and insert it into the view
<? echo $userPresentation->getHtml(); ?>

. , ( ) .

+2

, null , , , , , - .

Null Object.
, , - :

class NullAddress implements AddressInterface { }

Address AddressInterface.
getAddress() :

public function getAddress(): AddressInterface {
    return $this->address ?? new NullAddress();
}

, getAddress(), :

if ($user->getAddress() instanceof NullAddress) {
    // Implement result of empty address here.
}

. empty(), .

0

All Articles