Maison  >  Article  >  développement back-end  >  php如何在一个类中引入另外一个类

php如何在一个类中引入另外一个类

高洛峰
高洛峰original
2016-11-28 16:46:261799parcourir

有时候需要在一个类中调用另外一个类里面的方法,

然后另外一个类又需要调用当前类的方法,怎么办呢?

可以直接引入类对象的方式调用另外一个类的方法

示例如下(传值方式)

class a {
    function b($obj) {
        $obj->test();
    }
}
  
class b {
    function test() {
        echo 'test';
    }
}
  
$a = new a();
$b->b(new b());

继承的方式,如果子类中定义了相同的方法 将会覆盖父类的方法

class b {
    function __construct(){
      
    }
  
    function testb(){
        echo 'test';
    }
}
class a extends b {
    function __construct(){
        parent::testb();
        //or like this
        $this->testb();
    }
    //重复定义 将会覆盖
    function testb(){
        echo 123;
    }
}
  
$a = new a();


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn