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

WBOY
Release: 2016-06-06 20:24:32
Original
1636 people have browsed it

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>
Copy after login

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

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

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

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

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template