本文實例講述了php判斷某個方法是否存在函數(shù)function_exists (),method_exists()與is_callable()區(qū)別與用法。分享給大家供大家參考,具體如下:
php函數(shù)function_exists (),method_exists() 與is_callable()的區(qū)別在哪?
先來講下后兩個:method_exists() 與is_callable():
在php面相對象設(shè)計過程中,往往我們需要在調(diào)用某一個方法是否屬于某一個類的時候做出判斷,常用的方法有 method_exists()和is_callable()
相比之下,is_callable()函數(shù)要高級一些,它接受字符串變量形式的方法名作為 第一個參數(shù),如果類方法存在并且可以調(diào)用,則返回true。如果要檢測類中的方法是否能被調(diào)用,可以給函數(shù)傳遞一個數(shù)組而不是類的方法名作為參數(shù)。數(shù)組必須包含對象或類名,以將其作為它的第一個元素,要檢查的方法名則作為第二個元素。如果該方法在類中存在,函數(shù)返回true。
接下來看一段代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php class test { public function a() { return "test" ; } } class abc{ public function a( $object , $funcname ) { if (! is_callable ( array ( $object , $funcname ))) { //檢測方法:$funcname是否存在于$object中,并且屬于正常的調(diào)用結(jié)構(gòu) echo "error: the" . " " . $funcname . " no exist in " . $object . "</br>" ; } else { echo "ok" ; } } } $abc = new abc(); $abc ->a( "test" , "111" ); $abc ->a( "test" , "a" ); |
結(jié)果顯示如圖:
那么 如果把test類中的a方法改成私有的 或者是 受保護的 將會是什么樣的結(jié)果呢?
代碼如圖:
結(jié)果如圖:
好了我們再來看一下 method_exists()這個函數(shù):
結(jié)果:
到這里結(jié)論不用講也應(yīng)該清楚了吧?
php中的method_exists()和is_callable()的區(qū)別是什么呢?
php函數(shù)method_exists()與is_callable()的區(qū)別在于在php5中,一個方法存在并不意味著它就可以被調(diào)用。對于 private,protected和public類型的方法,method_exits()會返回true,但是is_callable()會檢查存在其是否可以訪問,如果是private,protected類型的,它會返回false。
然后還剩下一個 function_exists(),
這個比上兩個的檢測強度來講是最弱的 因為 只有一個參數(shù) 函數(shù)名 $string 只會判斷函數(shù)有沒有被定義
總結(jié)一下:
function_exists 比較簡單點就是判斷函數(shù)有沒有被定義 而method_exists 是判斷類內(nèi)的方法存不存在 is_callable 檢測參數(shù)是否為合法的可調(diào)用結(jié)構(gòu)
返回值 都是 bool
希望本文所述對大家PHP程序設(shè)計有所幫助。
原文鏈接:https://www.cnblogs.com/imnzq/p/6869811.html