0

I'm very new with PHP and OOP techniques.

So I have no problem creating a object like so:

$member1 = new Member('person 1');

But is there a way to return a bunch of objects. So that I can iterate through them and put them in the DOM?

0

2 Answers 2

1
class Example
{
    public function getPeople()
    {
        $objs = array();
        for($i = 0; $i < 10; $i++)
        {
            $obj[] = new Person('Person ' . ($i + 1));
        }
        return $objs; // returning an array of Person objects
    }
}
$example = new Example();
foreach($example->getPeople() as $person)
{
    // Do something with $person
}
Sign up to request clarification or add additional context in comments.

12 Comments

Can I create a Class, that returns an array of objects? I want to search for some members, and then display them in the DOM.
You can create a method that returns an array of objects. Class - code abstraction. Object - instantiation of a class.
@Gamak: No, you cannot have a class constructor return a value.
What I mean to ask is, Can I put a method in a class that returns a bunch of objects?
@Gamak Sure, you can make it a static method so that it's not related to a specific object but can be called generally.
|
0

In order to get objects, one possible way is to use array :-

$members = new members( array(...));
// you can assess any member via $members->members[$some_id] 

// class to return list of members
class members ()
{
  public $members = array();
  public function __construct( array $ids)
  {
    foreach ($id as $id)
    {
      $this->members[$id] = new Member($id);
    }
  }
}

class member()
{
  public function __construct($id)
  {
    // any other thing you want to do
  }
}

Comments

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.