这不是一个很好的示例,但它没有任何默认值。您可以确定的是,该getIsGuest方法将始终返回一个布尔值(true或false)。在您的代码片段中,它将始终返回 false,因为它使用另一个方法 ( getState) 的返回值并将其与null严格的 (值和类型) 进行比较。由于getState成员函数在您的示例中被硬编码为返回一个字符,因此它永远不会返回 null,因此getIsGuest将始终返回 false。
PHP 将null所有没有显式 return 语句的函数或方法作为其默认返回值(构造函数可能例外,它返回一个对象的实例)。就像 JSundefined默认会返回一样(构造函数除外),或者 C 函数可以返回void,但那是另一回事。
简而言之:不,您的代码没有设置默认返回值。我将尝试通过稍微编辑您的代码段来澄清所有这些:
class md
{
private $_mdData = array();//no data
public function __construct(array $params = null)//default value of $params is null
{//the constructor expects either no parameters, or an array
if ($params !== null)
{
$this->_mdData = $params;
}
if($this->getIsGuest())
{
echo 'I\'m guest';
}
}
public function getIsGuest()
{
return $this->getState('__id') === null;
}
public function getState($val)
{//return whatever value is stored in the private array under $val-key
//if the key doesn't exist, null is returned
return (isset($this->_mdData[$val]) ? $this->_mdData[$val] : null);
}
}
$guest = new md();//no params
构造函数调用getIsGuest,它试图访问$ mdData['_id ']
$_mdData 为空,所以key 不存在,返回null 给getIsGuest。
getIsGuest 将返回值 (null) 与 null 进行比较,并返回 true(因为它们相同)
构造函数接收 true,因为那getIsGuest是调用方法的地方,并评估值if ($this->getIsGuest())--> true,因此I'm a guest被回显。
$nonGuest = new md(array('__id'=>123));//same drill, only this time getState will return 123, and getIsGuest returns false
==现在和之间的区别===:
$nullish = new md(array('__id' => ''));
这不会回显我是客人,除非您要更改return $this->getState('__id') === null;为,return $this->getState('__id') == null;因为''空字符串是空字符串,例如0虚假等...