2

I am trying to store a collection of objects and can't call object methods in a foreach loop. This is basically what I have. The print function prints nothing. Is there something I am over looking or is this not the way to go about it?

class person
{
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function get_name() {
        return $this->name;
    }
}

$test_set[] = new person("John");
$test_set[] = new person("Jane");

foreach($test_set as $set_item) {
    print $set_item->get_name();
}
4
  • 1
    I copy-pasted your code and it works fine. The problem is somewhere else. Do you have error reporting turned on? Commented Apr 25, 2012 at 20:08
  • This is a simplified version of my code. I copy pasted it, and it worked too. It must be something in my more advanced class. Commented Apr 25, 2012 at 20:14
  • Try this code. It might be the multiple parameter construct? gist.github.com/a7e525e84cb95057a676 Commented Apr 25, 2012 at 20:23
  • 2
    Another typo, it's called __construct()... Commented Apr 25, 2012 at 20:31

2 Answers 2

3

You need to set your name like this (probably just a typo):

public function __construct($name) {
    $this->name = $name; // not $this->$name
}
Sign up to request clarification or add additional context in comments.

4 Comments

That was a typo on here. It still does not change the blank output.
Well for me it works in a test file. Any error output with error_reporting(E_ALL); ini_set('display_errors', '1'); at the top?
@DanLee I did set both of those, and everything is good. It is just printing nothing.
Try it with echo then? I can't explain this behaviour. Or you need to give us more of the code.
2

Your loop is working. But your class contains a mistake.

Replace:

    public function __construct($name) {
        $this->$name = $name;
    }

With:

    public function __construct($name) {
        $this->name = $name;
    }

1 Comment

Ugh @ anonymous down-votes. Maybe because the downvoter thought it came several minutes later than a very similar answer. But is still correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.