php and using composition
So I have the following which errors out but it seems like php sho开发者_JAVA百科uld recognize that it only needs only one copy. Should I create this as a reference to remove cirucular instantion of new objects?
<?php
class A {
public function __construct(){
echo "within A<br />";
$this->b=new &B();
}
}
class B{
public function __construct(){
echo "within B<br />";
$this->a=new A();
}
}
$jt=new A();
$ar=new B();
thx
edit - ? could have been asked better. I'm aware of most of issues brought up. Will move to static functions.
Do it like this:
<?php
class A {
public function __construct(){
echo "within A<br />";
}
public function setB(B $b) {
$this->b = $b;
}
}
class B{
public function __construct(A $a){
echo "within B<br />";
$this->a = $a;
}
}
$a=new A();
$b=new B($a);
$a->setB($b);
As others already mentioned in the comments:
- You don't need
&
as objects are always references - PHP can't know what you want, new always creates a new object
- If you want to limit the numebr of objects of a class use the singleton pattern
精彩评论