purencool Posted April 21, 2011 Share Posted April 21, 2011 I have instantiated a object and the constructor has an other object added the issue arises when I extent the first object how do I access the object in the variable. below is a stripped down example. I want accessfoo to access class a method foo that is stored in a var in class b is this possible. class a { private function foo(){ return "hello word"; } } $a = new a() class b { private $obj; public function __construct ($obj){ $this->obj= $obj; } } class c extends b{ private function accessfoo(){ $this->obj ????????????? } $c = new class($a) Link to comment https://forums.phpfreaks.com/topic/234315-object-orientation-question/ Share on other sites More sharing options...
requinix Posted April 21, 2011 Share Posted April 21, 2011 If you want foo() and $obj private then no*. * Unless you use reflection, which is not the solution to badly-designed objects. Link to comment https://forums.phpfreaks.com/topic/234315-object-orientation-question/#findComment-1204359 Share on other sites More sharing options...
purencool Posted April 21, 2011 Author Share Posted April 21, 2011 ok then how could I use a similar class layout but change the methods? what syntax would I need? Link to comment https://forums.phpfreaks.com/topic/234315-object-orientation-question/#findComment-1204373 Share on other sites More sharing options...
JonnoTheDev Posted April 21, 2011 Share Posted April 21, 2011 I suggest reading the following examples: http://php.net/manual/en/language.oop5.visibility.php Here are the correct access levels for your class methods: <?php class a { public function foo() { print "hello word"; } } class b { protected $obj; public function __construct($obj) { $this->obj = $obj; } } class c extends b { public function accessfoo(){ $this->obj->foo(); } } $a = new a(); $c = new c($a); $c->accessfoo(); ?> Link to comment https://forums.phpfreaks.com/topic/234315-object-orientation-question/#findComment-1204384 Share on other sites More sharing options...
purencool Posted April 21, 2011 Author Share Posted April 21, 2011 thank you very much. It would have taken me a month to work it out. Link to comment https://forums.phpfreaks.com/topic/234315-object-orientation-question/#findComment-1204654 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.