问题
How do I from PHP code if a PECL extension is installed or not?
I want gracefully handle the case when an extension is not installed.
回答1:
Couple different ways. You can just check for the existence of the class, or even a function: class_exists, function_exists, and get_extension_funcs:
<?php
if( class_exists( '\Memcached' ) ) {
// Memcached class is installed
}
// I cant think of an example for `function_exists`, but same idea as above
if( get_extension_funcs( 'memcached' ) === false ) {
// Memcached isn't installed
}
You can also get super complicated, and use ReflectionExtension. When you construct it, it will throw a ReflectionException. If it doesnt throw an exception, you can test for other things about the extension (like the version).
<?php
try {
$extension = new \ReflectionExtension( 'memcached' );
} catch( \ReflectionException $e ) {
// Extension Not loaded
}
if( $extension->getVersion() < 2 ) {
// Extension is at least version 2
} else {
// Extension is only version 1
}
回答2:
I think the normal way would be to use extension-loaded.
if (!extension_loaded('gd')) {
// If you want to try load the extension at runtime, use this code:
if (!dl('gd.so')) {
exit;
}
}
回答3:
get_loaded_extensions fits the bill.
Use like this:
$ext_loaded = in_array('redis', get_loaded_extensions(), true);
回答4:
Have you looked at get_extension_funcs?
来源:https://stackoverflow.com/questions/16612794/how-to-check-if-pecl-extension-is-present