PHP中无默认值的可选参数疑问——以PDO构造方法为例
Great question! This is a super common point of confusion when working with PHP's extension-based classes like PDO, so let's break this down clearly and practically.
The Core Reason: PDO is a C-Implemented PHP Extension
First off, unlike classes you write in plain PHP (where optional parameters must have explicit default values in the function signature), PDO is built as a PHP extension using C. The function signatures you see in documentation or IDE tooltips are just human-readable summaries generated from the extension's metadata—they don't always display the default values that are handled behind the scenes in C code.
How the Optional Parameters Work Under the Hood
Extension functions (including the PDO constructor) rely on PHP's internal C API to parse and handle parameters. Here's a simplified look at how it works for PDO:
- The C code uses functions like
zend_parse_parametersto define which parameters are optional. - For each optional parameter, the C logic sets a sensible default if the caller doesn't provide it:
- If you only pass
$dsn, the code defaults$usernameand$passwordto empty strings, and$optionto an empty array. - If you pass
$dsn+$username,$passworddefaults to an empty string and$optionto an empty array, and so on.
- If you only pass
This is why you can call new PDO($dsn) or new PDO($dsn, $user) without getting a "missing parameter" error—even though the formal signature you see doesn't list default values.
How to Confirm Valid Usage
You can always refer to the official PHP documentation for the PDO constructor: it explicitly marks $username, $password, and $option as optional. That's the definitive signal these parameters can be omitted, regardless of whether the signature shows default values.
For example, all these calls are perfectly valid:
// Full parameter set $dbh = new PDO($dsn, $username, $password, $options); // Omit the options array $dbh = new PDO($dsn, $username, $password); // Omit password and options $dbh = new PDO($dsn, $username); // Only the DSN provided $dbh = new PDO($dsn);
Every one of these works because the extension's C code handles missing parameters with built-in defaults.
内容的提问来源于stack exchange,提问作者Samwyzz

