moon 111 Posted October 25, 2008 Share Posted October 25, 2008 Can someone please explain to me why the following isn't working? <?php Class Nested { public $narray = array(); public $text; public function __construct($text) { $this->text = $text; } public function add(Nested $nested) { $array[] = $nested; } public function display() { echo $this->text; } } $nested = new Nested('First1'); $nested->add(new Nested('Second1')); $nested->add(new Nested('Second2')); $nested->narray[0]->display(); ?> This is the error: Fatal error: Call to a member function display() on a non-object in C:\wamp\www\nested.php on line 28 Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/130084-oo-help/ Share on other sites More sharing options...
DarkWater Posted October 25, 2008 Share Posted October 25, 2008 <?php class Nested { public $nest = array(); private $text; public function __construct($text) { $this->$text = $text; } public function add(Nested $nested) { $this->nest[] = $nested; } public function getText() { return $this->text; } } $n = new Nested('foo'); $n->add(new Nested('one')); $n->add(new Nested('two')); echo $n->nest[0]->getText(); There you go. Quote Link to comment https://forums.phpfreaks.com/topic/130084-oo-help/#findComment-674474 Share on other sites More sharing options...
Daniel0 Posted October 25, 2008 Share Posted October 25, 2008 Since when did explaining something become the same as giving a solution? Teacher: Find x in: 5x=10 Student: How do you do that? Teacher: 2 Quote Link to comment https://forums.phpfreaks.com/topic/130084-oo-help/#findComment-674601 Share on other sites More sharing options...
DarkWater Posted October 25, 2008 Share Posted October 25, 2008 Since when did explaining something become the same as giving a solution? Teacher: Find x in: 5x=10 Student: How do you do that? Teacher: 2 To be honest, I had to write up the code anyway to test it out, but I see your point. Here's an explanation: When you used the add() method, you were giving a local function variable named $array a new element. In order for the object to actually have it, you'd need to use $this->narray instead of $array. Quote Link to comment https://forums.phpfreaks.com/topic/130084-oo-help/#findComment-674613 Share on other sites More sharing options...
moon 111 Posted October 26, 2008 Author Share Posted October 26, 2008 Ah, yes, I just noticed that. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/130084-oo-help/#findComment-674928 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.