Skip to content

Instantly share code, notes, and snippets.

@RyujiAMANO
Last active April 4, 2019 12:20
Show Gist options
  • Save RyujiAMANO/e71b52247cb5c3ed739d98abf03eef00 to your computer and use it in GitHub Desktop.
Save RyujiAMANO/e71b52247cb5c3ed739d98abf03eef00 to your computer and use it in GitHub Desktop.
string or null を返すメソッドで型宣言できない
<?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;
}
}
@RyujiAMANO
Copy link
Author

https://twitter.com/RyujiAMANO/status/1113655976756834304
@suin さんに教えてもらった。 ?string でstring|null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment