Say you have two classes, A and B. Is it possible to instantiate both classes once and then let class B call methods in class A, and vice versa?
It can be done using double colon (::) … … but then the method becomes static – is that a disadvantage? (see example below)
Can it be done in other ways? With interfaces?
This code shows what I try to do:
class A {
function horse() {
echo "horse";
}
}
class B {
function jump() {
// $A = new A; ... don't want to add this in each method.
$A->horse(); // Fails - $A is out of scope ($A = new A;).
// A::horse(); // Old code style - works.
// $this->horse(); // Works if you extend A - not self-documenting.
// $this->A->horse(); // Fails - out of scope.
}
}
$A = new A;
$B = new B; // Better to use "$B = new B($A);" ?
$B->jump(); // fails - the horse is sleeping.
Edit
Well, I am building a MVC-framework and I want to re-use code from other classes.
Some real-world examples:
- a database object that is being passed across classes.
- a “url” class that creates/manipulates URLs – used by other classes.
-
… and a code example:
class url { function anchor($url,$name) { return "<a href="{$url}\">{$name}</a>"; } } class someclass { function text($str,$url) { return "{$str}. " . $url->anchor($url,"Read more..."); } }
I think what you are asking for is multiple inheritance where you could extend both A and B like this
This however is not possible in PHP for good reasons(it actually is creating more problems than it’s trying to solve).
Now you might ask yourself if there is any alternative to multiple inheritance and the answer is: Yes, there is! Have a look at the strategy pattern(as Benjamin Ortuzar also has pointed out).
UPDATE:
I just read your question a second time and figured that you might be looking for the singleton pattern, which lets you instantiate an instance of an class only once like this:
Now
A::getInstance()always returns the same instance of A which you can use in B and you can have both the advantages of dynamic functions and the accessibility of static functions.UPDATE2:
Your database belongs into a registry if you can have more than one db-connection. If you’re absolutely certain that you will always need only one db-connection you could as well make it a singleton.
For the URL helper I’d suggest writing a static class if you can and if you really need it to be dynamic make it a singleton, as mentioned before.