0

Possible Duplicate:
Instance as a static class property

I got a problem about creating an Object in a class as an attribute.

include 'Bar.php';
class Foo()
{
    private $bar = new Bar();
}

It comes out a parse error. But when I put the $bar outsite class

include 'Bar.php';
class Foo()
{
    //private $bar = new Bar();
}
$bar = new Bar();

No syntax error. works perfectly. So what's the problem. I just ported my Java knowledge to PHP. Sometimes, its so confusing.

Community
  • 1
  • 1
Hoan Dang
  • 366
  • 1
  • 6
  • 14
  • It's not possible; there is a long discussion on why, check it out:[Why don't PHP attributes allow functions?](http://stackoverflow.com/q/3960323) – Pekka Feb 18 '12 at 10:55
  • more: http://stackoverflow.com/search?q=[php]+body%3A%22initialization+must+be+a+constant+value%22 – Gordon Feb 18 '12 at 11:24
  • @Gordon the question linked above is the only thing close to a canonical explanation attempt. I know of no more; might just upvote your dupe-link so it becomes more visible in the close dialog... Do you think it's worth adding to the Tag Wiki? – Pekka Feb 18 '12 at 11:28
  • @Pekka IMO the tag wiki is worthless because no one looks into it, but sure, go ahead and add it ;) Though I think it would make more sense to go through the search, hijack one question, rewrite it and have the good answers merged into it. – Gordon Feb 18 '12 at 11:30
  • @Gordon will do. We should be able to close questions as a duplicate of the Tag Wiki. *That* would increase its visibility :) – Pekka Feb 18 '12 at 11:31
  • @Pekka I'm still convinced it needs subpages (like Operator reference) – Gordon Feb 18 '12 at 11:33

2 Answers2

2

You have to put it into the constructor:

class Foo() {
    private $bar;
    function __construct() {
        $this->bar = new Bar();
    }
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
0
class Foo {
    private $bar;

    public function __construct() {
      $this->bar = new Bar();
    }

    public function check() {
      return $this->bar->checkBack();
    }
}

class Bar {
  public function __construct() {
    print "good\n";
  }

  public function checkBack() {
    return "checked";
  }
}

$f = new Foo();
print $f->check();
busypeoples
  • 737
  • 3
  • 6