How to check if PECL extension is present?

亡梦爱人 提交于 2019-12-10 12:49:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!