Let's say I have three classes. One being the parent and two being "childs". However, I'm not using class - extends -
:
class root
{
function 开发者_运维百科root(){
$this->son = new son();
$this->daughter = new daughter();
}
}
class son
{
...
}
class daughter
{
...
}
How could I call a function of son from a function of daughter? In other words, how could I reference the class root from son/daughter so that I could call functions of each other, from each other?
A classic case of dependency injection.
class root {
function root() {
$this->son = new son($this);
$this->daughter = new daughter($this);
}
}
class son {
function __construct($parent) {
$this->parent = $parent;
}
function foo() {
$this->parent->daughter->bar();
}
}
Just be careful not to create rigid dependencies between classes that shouldn't have them. Inheritance may be the better way to go. Alternatives include the registry pattern and factory patterns.
The only possible way here is to explicitly pass the reference to your root class object:
function root(){
$this->son = new son($this);
$this->daughter = new daughter($this);
}
And accept it in the son
and daughter
constructors.
class son
{
private $root;
public function son($root)
{
$this->root = $root;
}
}
class daughter
{
private $root;
public function daughter($root)
{
$this->root = $root;
}
public function doSomethingToBrother()
{
$this->root->son->some_method();
}
}
Since son and daughter aren't actually subclasses of root, the only way to call each other's functions is to get an instance and call from there. Unless the functions are declared static, in which case you can call them via son::my_func() / daughter::my_func, etc.
I'm not sure what the goal is, but maybe this will help: http://php.net/manual/en/language.oop5.patterns.php
You will have to pass an instance of root to son or daughter if you want to call methods between them. Or if it is something that does not depend on the instance, use static methods.
Example, hopefully speaking for itself, with the important lines being:
a) $this->son = new Son($this);
– where a reference to the Root
object is passed to a new Son
class (or Daughter
respectively).
b) echo $son->root->daughter->aboutme();
– where the reference is used to access other objects, root might have access to.
One can consider this a kind of Mediator pattern.
<?php
class Root
{
function __construct(){
$this->son = new Son($this);
$this->daughter = new Daughter($this);
}
function aboutme() { print "I'm root.\n"; }
}
class Son
{
function __construct($root) {
$this->root = $root;
}
function aboutme() { print "I'm a son.\n"; }
}
class Daughter
{
function __construct($root) {
$this->root = $root;
}
function aboutme() { print "I'm a daughter.\n"; }
}
$root = new Root();
echo $root->aboutme();
$son = $root->son;
echo $son->aboutme();
echo $son->root->daughter->aboutme();
?>
This will yield:
I'm root.
I'm a son.
I'm a daughter.
精彩评论