Heim  >  Artikel  >  Backend-Entwicklung  >  php判断一个类方法是否存在

php判断一个类方法是否存在

WBOY
WBOYOriginal
2016-06-20 13:00:333125Durchsuche

php判断一个类方法是否存在

做php开发中,如果遇到自己不能修改服务器的相关配置也不能知道服务器某些功能是否开启的情况下,直接使用某些特殊的函数会导致程序报错,比如curl_init这种系统函数。当服务器未开启curl相关服务的时候,直接使用curl系列函数会报Call to undefined function curl_init()......这样的错误。

那么对于出现这种情况该如何办呢?很多事情不只是有一种办法的,如果某些方法不行,我们还可以使用另外的方法。这里我们就需要涉及到判断某个方法是否存在的问题了,如果存在该方法则使用该方法,如果不存在该方法则使用另外的方法。

这里对于如何判断一个函数,类以及类中的方法是否存在做了一个整理:

(1)php判断系统函数或自己写的函数是否存在

bool function_exists ( string $function_name ) 判断函数是否已经定义,例如:

if(function_exists('curl_init')){
	curl_init();
}else{
	echo 'not function curl_init';
}

(2)php判断类是否存在

bool class_exists ( string $class_name [, bool $autoload = true ] ) 检查一个类是否已经定义,一定以返回true,否则返回false,例如:

if(class_exists('MySQL')){
    $myclass=new MySQL();
}

(3)php判断类里面的某个方法是否已经定义

bool method_exists ( mixed $object , string $method_name ) 检查类的方法是否存在,例如:

$directory=new Directory;
if(!method_exists($directory,'read')){
	echo '未定义read方法!';
}


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn