i am a new PHP, i have some files like this:
In root.php i have
<?php
class Root
{
// Some functions here
}
In child_1.php i have:
class Child_1 extends Root
{
function abc()
{
//Some code here
}
}
In child_2.php i have:
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.
As classes that extend one parent ( Root
) know nothing about each other (and you cannot change this), you can do:
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:
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. This will allow you to call functions of Chirld_1 from Chirld_2 and vice verse using the $this keyword. 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
Try using parent:: or static:: or self:: notation to designate the class you want to use. http://php.net/manual/pl/keyword.parent.php
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.