简体   繁体   English

从子类PHP调用子类

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

i am a new PHP, i have some files like this: 我是一个新的PHP,我有一些像这样的文件:

In root.php i have 在root.php我有

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

In child_1.php i have: 在child_1.php中,我有:

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

In child_2.php i have: 在child_2.php中,我有:

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

Yes, how can i call a function of Child_1 class from a function of Child_2 class. 是的,我如何从Child_2类的函数中调用Child_1类的函数。

As classes that extend one parent ( Root ) know nothing about each other (and you cannot change this), you can do: 由于扩展一个父级( Root )的类彼此之间一无所知 (并且您不能更改此设置),因此可以执行以下操作:

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

But obviously it's a lack of good design. 但是显然这是缺乏好的设计。 I suppose, you have to define abc() in a Root class to make it available in both children: 我想,您必须在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

If you want to use functions of Chirld_1 from Chirld_2 or vice versa without creating an object of the child class, then one option is to declare Chirld_1 and Chirld_2 as traits of the parent class Root. 如果要使用Chirld_2中的Chirld_1的功能,反之亦然,而不创建子类的对象,则一种方法是将Chirld_1和Chirld_2声明为父类Root的特征。 This will allow you to call functions of Chirld_1 from Chirld_2 and vice verse using the $this keyword. 这将允许您使用$ this关键字从Chirld_2调用Chirld_1的函数,反之亦然。 The classes should be declared as follows: 这些类应声明如下:

<?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
}

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

Try using parent:: or static:: or self:: notation to designate the class you want to use. 尝试使用parent ::或static ::或self ::表示法来指定要使用的类。 http://php.net/manual/pl/keyword.parent.php http://php.net/manual/pl/keyword.parent.php

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

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