Last active
April 4, 2019 12:20
-
-
Save RyujiAMANO/e71b52247cb5c3ed739d98abf03eef00 to your computer and use it in GitHub Desktop.
string or null を返すメソッドで型宣言できない
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// PHP7.1以上だったらこれでOK | |
class UserPHP71 { | |
/** | |
* @var string | |
*/ | |
private $name; | |
/** | |
* @var string|null | |
*/ | |
private $otherName; | |
public function __construct(string $name, string $otherName = null) { // string $otherName = null だとstringもnullもわたせる | |
$this->name = $name; | |
$this->otherName = $otherName; | |
} | |
/** | |
* @return string | |
*/ | |
public function getName() : string { | |
return $this->name; | |
} | |
/** | |
* @return string|null | |
*/ | |
public function getOtherName() : ?string { | |
return $this->otherName; | |
} | |
} | |
$user = newUserPHP71('Ryuji'); | |
echo $user->getOtherName(); // echo nullになる | |
class User { | |
/** | |
* @var string | |
*/ | |
private $name; | |
/** | |
* @var string|null | |
*/ | |
private $otherName; | |
public function __construct(string $name, string $otherName = null) { // string $otherName = null だとstringもnullもわせる | |
$this->name = $name; | |
$this->otherName = $otherName; | |
} | |
/** | |
* @return string | |
*/ | |
public function getName() : string { | |
return $this->name; | |
} | |
/** | |
* @return string|null | |
*/ | |
public function getOtherName() : string { | |
return $this->otherName; | |
} | |
} | |
$user = new User('Ryuji'); | |
echo $user->getOtherName(); // <- Fatal error: Uncaught TypeError: Return value of User::getOtherName() must be of the type string, null returned | |
class User改 { | |
/** | |
* @var string | |
*/ | |
private $name; | |
/** | |
* @var string|null | |
*/ | |
private $otherName; | |
public function __construct(string $name, string $otherName = null) { | |
$this->name = $name; | |
$this->otherName = $otherName; | |
} | |
/** | |
* @return string | |
*/ | |
public function getName() : string { | |
return $this->name; | |
} | |
/** | |
* @return string|null | |
*/ | |
public function getOtherName() { //<- 戻り値型を指定できないのがきになる | |
return $this->otherName; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://twitter.com/RyujiAMANO/status/1113655976756834304
@suin さんに教えてもらった。
?string
でstring|null