Jump to content

Recommended Posts

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!

Link to comment
https://forums.phpfreaks.com/topic/130084-oo-help/
Share on other sites

<?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.

Link to comment
https://forums.phpfreaks.com/topic/130084-oo-help/#findComment-674474
Share on other sites

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.

Link to comment
https://forums.phpfreaks.com/topic/130084-oo-help/#findComment-674613
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.