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!" 开发者_JS百科or not?
Will this echo "hi!" or not?
No
Change this line:
$bar = new bar();
to:
$this->bar = new bar();
to output:
hi!
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();
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...
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)
精彩评论