繁体   English   中英

从子类PHP调用子类

[英]Call a child class from a child class PHP

我是一个新的PHP,我有一些像这样的文件:

在root.php我有

<?php
class Root
{
// Some functions here
}

在child_1.php中,我有:

class Child_1 extends Root
{
  function abc()
  {
  //Some code here
  }
}

在child_2.php中,我有:

class Child_2 extends Root
{
  function cde()
  {
  // How can i call function abc() from class Child_1 here
  }
}

是的,我如何从Child_2类的函数中调用Child_1类的函数。

由于扩展一个父级( Root )的类彼此之间一无所知 (并且您不能更改此设置),因此可以执行以下操作:

class Chirld_2 extends Root
{
  function cde()
  {
    $obj = new Chirld_1();
    $obj->abc();
  }
}

但是显然这是缺乏好的设计。 我想,您必须在Root类中定义abc()才能在两个子级中均可用:

class Root
{
  function abc()
  {
  //Some code here
  }
}

class Chirld_1 extends Root
{

}

class Chirld_2 extends Root
{

}

$c1 = new Chirld_1();
$c1->abc();
$c2 = new Chirld_2();
$c2->abc();

您可以调用父类的class_1或Class_2中的任何函数,但不能在任何子类中调用另一个函数。因为它们没有关联,因此解决方案是您在class_1的构造函数中调用class_2

如果要使用Chirld_2中的Chirld_1的功能,反之亦然,而不创建子类的对象,则一种方法是将Chirld_1和Chirld_2声明为父类Root的特征。 这将允许您使用$ this关键字从Chirld_2调用Chirld_1的函数,反之亦然。 这些类应声明如下:

<?php

trait Chirld_1
{
    public function test1()
    {
       $this->test2();
    }        
}

trait Chirld_2
{
    public function test2()
    {
       $this->test1();
    }   
}

class Root
{
    use Chirld_1;
    use Chirld_2;
// Some functions here
}

请参阅此链接以获取有关特征的更多信息: http : //php.net/manual/en/language.oop5.traits.php

尝试使用parent ::或static ::或self ::表示法来指定要使用的类。 http://php.net/manual/pl/keyword.parent.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM