我有一个函数“isValid”,它负责在提供的所有变量中搜索空格。如果没有任何变量包含空格,我希望函数返回 true。这是正确的方法吗?
return !(strpos($this->email, " ") || strpos($this->confirm_password1, " ") || strpos($this->handle, " ") || strpos($this->phone, " "));
我有一个函数“isValid”,它负责在提供的所有变量中搜索空格。如果没有任何变量包含空格,我希望函数返回 true。这是正确的方法吗?
return !(strpos($this->email, " ") || strpos($this->confirm_password1, " ") || strpos($this->handle, " ") || strpos($this->phone, " "));
为了使其易于维护,我将执行以下操作:
public function isValid()
{
$properties = array(
'email',
'confirm_password1',
'handle',
'phone',
);
foreach ($properties as $property) {
if ($this->containsSpace($property)) {
return false;
}
}
return true;
}
private function containsSpace($property)
{
return !(strpos($this->$property, '') === false);
}
注意=== false
as 检查strpos()
. 演示:http ://codepad.viper-7.com/0ZgNZq 。
请注意,这仅检查空格,而不检查其他可能的空白字符。如果您想检查其他空白字符,我建议使用简单的正则表达式:
private function containsSpace($property)
{
return (bool)preg_match('/\s/', $this->$property);
}
最后,如果您真的想以原始方式进行操作,我会执行以下操作:
public function isValid()
{
return strpos($this->email, " ") === false && strpos($this->confirm_password1, " ") === false && strpos($this->handle, " ") === false && strpos($this->phone, " ") === false;
}
return (strpos($this->email, " ") === false && strpos($this->confirm_password1, " ") === false && strpos($this->handle, " ") === false && strpos($this->phone, " ") === false)
but this makes for fairly unreadable code...
function isValid($var) {
if (strpos($var, ' ') === false) {
// Does not contain a space character.
return true;
}
return false;
}