method_exists()和is_callable()方法進行判斷。那么兩則區別是什么呢?
已知類文件如下:
class Student{
private $alias=null;
private $name='';
public function __construct($name){
$this->name=$name;
}
private function setAlias($alias){
$this->alias=$alias;
}
public function getName(){
return $this->name;
}
}
當方法是private,protected類型的,method_exists會報錯,is_callable會返回false。
實例
下面是判斷某一對象中是否存在方法getName
通過method_exists實現
$xiaoming=new Student('xiaoming');
if (method_exists($xiaoming, 'getName')) {
echo 'exist';
}else{
echo 'not exist';
}
exit();
輸出exist
通過is_callable實現
$xiaoming=new Student('xiaoming');
if (is_callable(array($xiaoming, 'getName'))) {
echo 'exist';
}else{
echo 'not exist';
}
exit();
輸出exist
下面是判斷某一對象中是否存在方法setAlias
當使用method_exists的時候報錯如下
當使用is_callable的時候,輸出not exist