I am experimenting with PHP OOP
what i’m trying to find out is, Is it possible to access a object instance from withing a object that was created in this object instance?
sounds confusing, so here is a example:
contents of index
class mainclass {
var $data;
function __construct($data){
$this->data = $data;
}
function echodata(){
echo $this->data;
}
function start($classname){
include $classname.'.php';
$inner = new $classname();
$inner->show();
}
}
$mainclass = new mainclass('maininfostuff');
$mainclass->start('innerclass');
//i want it to echo "maininfostuff"
contents of innerclass.php
class innerclass{
function show(){
mainclass->echodata();//the problem is here
}
}
the purpose of this test case is to make the inner class decide if/when to run the mainclass echodata function
how can the above example be accomplished? (without relying on static classes or singletons or extended classes)
edit:
due to some confusion in answers i have edited the example
Inner classes are not possible in PHP. So you cannot declare your innerclass within mainclass. And since you can’t do that, there’s no way to access the outer classes variables as you can in, for example, Java.
You can do this instead: