Reputation: 117
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.
Upvotes: 0
Views: 58
Reputation: 3763
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
Upvotes: 1
Reputation: 1680
you can call any function in class_1 or Class_2 of parent class but within any child class you can't call method from another.because They do not have a relevance a solution is you call class_2 in constructor of class_1
Upvotes: 1
Reputation: 54831
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();
Upvotes: 1
Reputation: 2194
Try using parent:: or static:: or self:: notation to designate the class you want to use. http://php.net/manual/pl/keyword.parent.php
Upvotes: 0