返回变量中空格的真值

时间:2012-12-05 17:21:52

标签: php function return whitespace

我有一个函数“isValid”,它负责在提供的所有变量中搜索空格。如果没有变量包含空格,我希望函数返回true。这是正确的做法吗?

return !(strpos($this->email, " ") || strpos($this->confirm_password1, " ") || strpos($this->handle, " ") || strpos($this->phone, " "));

3 个答案:

答案 0 :(得分:2)

为了使其易于维护,我会做类似以下的事情:

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 check for 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;
}

答案 1 :(得分:1)

function isValid($var) {
  if (strpos($var, ' ') === false) {
    // Does not contain a space character.
    return true;
  }
  return false;
}

答案 2 :(得分:1)

return (strpos($this->email, " ") === false && strpos($this->confirm_password1, " ")  === false && strpos($this->handle, " ") === false && strpos($this->phone, " ") === false)

但这会产生相当难以理解的代码...