Reports the current PHP version or the version of a named loaded extension.
What It Does and When to Use It
Read the current runtime version string. A minimum platform requirement controls what syntax can be parsed; target-version tests find runtime and extension incompatibilities.
Requirements, Inputs and Expected Behavior
Confirm the runtime, extension, environment variables, and permissions before running the examples in production. An extension can be loaded but not report a version; false must be handled.
Example 1: Basic Operation
Read the current runtime version string.
<?php
echo phpversion(), "
";
Example 2: Behavior and Validation
Ask for an extension-specific version and handle false.
<?php
$version = phpversion('Zend OPcache');
echo $version === false ? 'No extension version found' : $version;
Practical Example: Application Use
Gate a feature by comparing PHP versions numerically.
<?php
if (version_compare(phpversion(), '8.4.0', '<')) {
throw new RuntimeException('PHP 8.4 or later is required');
}
echo 'Compatible runtime';
Important Behavior and Edge Cases
The second example highlights: Ask for an extension-specific version and handle false. The practical example adds: Gate a feature by comparing PHP versions numerically.
Comparison with Related Approaches
| Approach | What changes |
|---|---|
| Minimum PHP version and target PHP version | A minimum platform requirement controls what syntax can be parsed; target-version tests find runtime and extension incompatibilities. |
| Choosing safely | Do not introduce syntax from a newer minor version before every production host supports it. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Assuming newer syntax parses on older PHP | Lint with the oldest supported runtime; gate or delay newer syntax. |
| Upgrading CLI PHP but not the web worker | Check the FPM binary, all extensions and the Composer platform in staging. |
| Skipping operational constraints | An extension can be loaded but not report a version; false must be handled. |
Key Takeaways
- Reports the current PHP version or the version of a named loaded extension.
- Gate a feature by comparing PHP versions numerically.
- Do not introduce syntax from a newer minor version before every production host supports it.