开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜