Created
August 16, 2012 11:20
-
-
Save upsilon/3369426 to your computer and use it in GitHub Desktop.
PHPでGETパラメータとかの空値チェックしたいんだけど何これ
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 | |
require_once '/path/to/lime.php'; | |
function test_empty_values($lime, $validator) | |
{ | |
/* これは空値と見なしたい */ | |
$lime->ok($validator(null), "null"); | |
$lime->ok($validator(''), "''"); | |
$lime->ok($validator(' '), "' '"); | |
/* これは空値と見なしたくない */ | |
$lime->ok(!$validator('foo'), "'foo'"); | |
$lime->ok(!$validator('0'), "'0'"); | |
$lime->ok(!$validator('1'), "'1'"); | |
$lime->ok(!$validator('true'), "'true'"); | |
$lime->ok(!$validator('false'), "'false'"); | |
} | |
$lime = new lime_test(); | |
$lime->diag('(bool)!$value'); /* ダメ */ | |
test_empty_values($lime, function ($value) { | |
return !$value; | |
}); | |
$lime->diag('is_null($value)'); /* ダメ */ | |
test_empty_values($lime, function ($value) { | |
return is_null($value); | |
}); | |
$lime->diag('empty($value)'); /* ダメ */ | |
test_empty_values($lime, function ($value) { | |
return empty($value); | |
}); | |
$lime->diag('$value = trim($value); empty($value)'); /* ダメ */ | |
test_empty_values($lime, function ($value) { | |
$value = trim($value); | |
return empty($value); | |
}); | |
/* ここから上はテスト通過しない */ | |
/* ここから下はテスト通過する */ | |
$lime->diag('$value = trim($value); empty($value) && !is_numeric($value)'); /* OK */ | |
test_empty_values($lime, function ($value) { | |
$value = trim($value); | |
return empty($value) && !is_numeric($value); | |
}); | |
$lime->diag('$value = trim($value); is_null($value) || 0 === strlen($value)'); /* OK */ | |
test_empty_values($lime, function ($value) { | |
$value = trim($value); | |
return is_null($value) || 0 === strlen($value); | |
}); |
(参考)PHP: PHP 型の比較表 - Manual
http://php.net/manual/ja/types.comparisons.php
一方、C#では string.IsNullOrWhiteSpace(value)
と書いた
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
実行結果