Heim  >  Artikel  >  Backend-Entwicklung  >  PHP父类的构造函数里面有办法判断子类有某个方法吗?

PHP父类的构造函数里面有办法判断子类有某个方法吗?

WBOY
WBOYOriginal
2016-06-06 20:24:321617Durchsuche

PHP父类的构造函数里面有办法判断子类有某个方法吗?

回复内容:

PHP父类的构造函数里面有办法判断子类有某个方法吗?

hongweipeng的代码有错误, $this应该改成$static.
不懂请google 后期静态绑定

修正:应该使用method_exists()
实例代码如下:

<code><?php class F{
    public function __construct(){
        if(method_exists($this, 'son_fun1')){
            echo 'son_fun1存在';
        }else{
            echo 'son_fun1不存在';
        }
        if(method_exists($this,'son_fun2')){
            echo 'son_fun2存在';
        }else{
            echo 'son_fun2不存在';
        }
    }
}
class S extends F{
    public function son_fun1(){
    }
}
$a = new S();</code></code>

<code>is_callable([$this, 'methodName'])</code>

但这并不是一个很好的设计。理论上父类不应当需要了解这个信息

通常情况下,这是不存在的。

但是,如果你指的子类是一个具体的,已知的子类,那么可以使用method_exists

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