Matthew Sainsbury
Matthew Sainsbury

Reputation: 1488

Classes within classes in PHP

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?

Upvotes: 0

Views: 242

Answers (4)

Artefacto
Artefacto

Reputation: 97805

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)

Upvotes: 0

Johannes Gorset
Johannes Gorset

Reputation: 8785

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();

Upvotes: 0

ircmaxell
ircmaxell

Reputation: 165191

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...

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382626

Will this echo "hi!" or not?

No

Change this line:

$bar = new bar();

to:

$this->bar = new bar();

to output:

hi!

Upvotes: 3

Related Questions