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
Once you have an object, you can use the -> notation to access methods and properties of the object: $object -> propertyname $object -> methodname ([ arg, ... ] ) Methods are functions, so they can take arguments and return a value: $clan = $rasmus->family('extended');
By comparing the two objects with the == operator, you can see if they have the same classes and attributes. if($box1 == $box2) echo 'equivalent'; You can further distinguish whether they refer to the same original object, and compare them in the same way: === operator: if($box1 === $box2) echo 'exact same object!
You create StdClass objects and access methods from them like so: $obj = new StdClass; $obj->foo = "bar"; echo $obj->foo; I recommend subclassing StdClass or creating your own generic class so you can provide your own methods. Thank you for your help!
The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.
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:
class mainclass {
var $data;
function __construct($data){
$this->data = $data;
}
function echodata(){
echo $this->data;
}
function start(){
$inner = new innerclass();
$inner->show($this);
}
}
class innerclass{
function show($mainclass){
$mainclass->echodata();//the problem is here
}
}
$mainclass = new mainclass('maininfostuff');
$mainclass->start();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With