tags:

views:

66

answers:

4

Can you do this in PHP? I've heard conflicting opinions:

Something like:

Class bar {
   function a_function () { echo "hi!"; }
}

Class foo {
   public $bar;
   function __construct() {
       $this->bar = new bar();
   }
}
$x = new foo();
$x->bar->a_function();

Will this echo "hi!" or not?

A: 

Yes, you can. The only requirement is that (since you're calling it outside both classes), in

$x->bar->a_function();

both bar is a public property and a_function is a public function. a_function does not have a public modifier, but it's implicit since you specified no access modifier.

edit: (you have had a bug, though, see the other answers)

Artefacto
Thanks. Thats what I thought, but my code always seems to fail right after I start making these nested classes. anyway... I must be the problem. ;)
Matt
@Matt PHP does not support nested classes. This is called object composition. See http://en.wikipedia.org/wiki/Object_composition
Artefacto
yeah i've caused a bit of confusion with my wording. I suppose what I really meant was nested objects. thanks for the help
Matt
+3  A: 
Sarfraz
Yeah :) sorry, forgot to do thatThanks
Matt
A: 

In a class, you need to prefix all member variables with $this->. So your foo class's constructor should be:

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

Then it should work quite fine...

ircmaxell
A: 

It's perfectly fine, and I'm not sure why anyone would tell you that you shouldn't be doing it and/or that it can't be done.

Your example won't work because you're assigning new Bar() to a variable and not a property, though.

$this->bar = new Bar();

Johannes Gorset
Thanks, realised that, and have changed the example
Matt