create_function() 允許根據條件在執行時建立函數,但已棄用移除。現代 PHP 使用匿名函數配合工廠函數實現相同目標,且更安全、效能更好。本文展示遷移範例。
<?php
if (count($_POST) > 0) {
$prepped = create_function('$a', 'return trim($_POST[$a]);');
} elseif (count($_GET) > 0) {
$prepped = create_function('$a', 'return strtoupper($_GET[$a]);');
} else {
$prepped = create_function('$a', 'return false;');
}
echo $prepped('file');
?>
<?php
function createProcessor(): callable {
if (!empty($_POST)) {
return fn($key) => trim($_POST[$key] ?? '');
} elseif (!empty($_GET)) {
return fn($key) => strtoupper($_GET[$key] ?? '');
} else {
return fn($key) => false;
}
}
$prepped = createProcessor();
echo $prepped('file');
?>
<?php
interface ProcessorInterface {
public function process(string $key): mixed;
}
class PostProcessor implements ProcessorInterface {
public function process(string $key): mixed {
return trim($_POST[$key] ?? '');
}
}
class GetProcessor implements ProcessorInterface {
public function process(string $key): mixed {
return strtoupper($_GET[$key] ?? '');
}
}
class NullProcessor implements ProcessorInterface {
public function process(string $key): mixed { return false; }
}
// 工廠
function getProcessor(): ProcessorInterface {
if (!empty($_POST)) return new PostProcessor();
if (!empty($_GET)) return new GetProcessor();
return new NullProcessor();
}
$processor = getProcessor();
echo $processor->process('file');
?>
動態建立函數需求應透過「工廠回傳匿名函數」或「策略模式」實現,徹底替代 create_function()。現代寫法更安全、更快、更易維護。希望本文對您的 PHP 程式設計有所幫助。