<?php
define('APP_VERSION', '1.0.0');
define('DEBUG_MODE', true);
if (defined('APP_VERSION')) {
echo "版本: " . APP_VERSION; // 版本: 1.0.0
}
// 檢查未定義常數
var_dump(defined('NON_EXISTENT')); // bool(false)
?>
注意: defined() 參數必須是字串,不要寫成 defined(APP_VERSION) (會先展開常數值)。
| 情況 | isset() 回傳 |
|---|---|
| 變數不存在 | false |
變數存在且值為 null | false |
變數存在且值非 null | true |
| 多變數同時檢查 | 全部 true 才回 true |
<?php
$var = '';
var_dump(isset($var)); // true (空字串非 null)
$arr = ['a' => 1, 'b' => null];
var_dump(isset($arr['a'])); // true
var_dump(isset($arr['b'])); // false ← 關鍵:值為 null 視為未設定
var_dump(isset($arr['c'])); // false
// 多變數
var_dump(isset($a, $b, $c)); // 任一 false 則整體 false
?>
<?php
$arr = ['key1' => 'value', 'key2' => null];
var_dump(array_key_exists('key1', $arr)); // true
var_dump(array_key_exists('key2', $arr)); // true ← 即使值為 null
var_dump(array_key_exists('key3', $arr)); // false
// 物件屬性用 property_exists()
class Demo { public $prop = null; }
$obj = new Demo();
var_dump(property_exists($obj, 'prop')); // true
var_dump(isset($obj->prop)); // false (值為 null)
?>
<?php
if (function_exists('json_encode')) {
echo 'JSON 支援可用';
}
// 檢查擴展函式
if (function_exists('curl_init')) {
echo 'cURL 擴展已載入';
}
// 類別方法需用 method_exists()
class A { public function foo() {} }
var_dump(method_exists(A::class, 'foo')); // true
var_dump(method_exists('A', 'foo')); // true (字串類別名也可)
?>
<?php
// 檢查 GET 參數是否存在
if (filter_has_var(INPUT_GET, 'id')) {
$id = (int)$_GET['id'];
}
// 檢查 POST
if (filter_has_var(INPUT_POST, 'username')) {
// ...
}
// 輸入類型常數
// INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV
?>
<?php
class_exists('DateTime'); // true
interface_exists('Countable'); // true
trait_exists('Stringable'); // PHP 8.0+
// 自動載入器註冊後才會觸發載入
spl_autoload_register(function($class) {
// ...
});
var_dump(class_exists('MyClass')); // 會觸發 autoload
?>
hasProperty('timezone'); // false (私有屬性)
$ref->hasMethod('format'); // true
$ref->hasConstant('ATOM'); // true
// 靜態檢查不實例化
$ref->getProperty('timezone')->isPublic(); // false
'value'];
$iterations = 1_000_000;
$start = hrtime(true);
for ($i=0;$i<$iterations;$i++) isset($arr['key']);
echo 'isset: ' . (hrtime(true)-$start)/1e9 . "s\n";
$start = hrtime(true);
for ($i=0;$i<$iterations;$i++) array_key_exists('key', $arr);
echo 'array_key_exists: ' . (hrtime(true)-$start)/1e9 . "s\n";
// isset 約快 3-5 倍
isset() (最快、語意清晰)array_key_exists()defined()function_exists()/method_exists()@ 抑制錯誤來檢查存在性 (效能差、隱藏真實錯誤)