开发者

How to cast an array of Objects

开发者 https://www.devze.com 2023-01-31 21:51 出处:网络
I\'m trying to cast an array of Objects for a week already in a PHP class and have had some real issues making it to work and mainly with the logic itself as I am new to classes. Looked and read a lot

I'm trying to cast an array of Objects for a week already in a PHP class and have had some real issues making it to work and mainly with the logic itself as I am new to classes. Looked and read a lot of resources but it does not seem to make any sense to me, any pointers would be greatly appreciated and I am open to suggestions.

The issue: Create a PHP class as part of the project named Contact, and then a class called 'ContactList' that contains an array of these contact objects.

And next, an array of ContactList objects called 'ContactTabs'.

Then, in the program, populate one ContactList object (named 'Contacts') with the current contacts, and create a new ContactList object named 'Friends', and add some names and email addresses there for friends. It is most important that this be done in a nice, object-oriented fashion so it can allow to create other type of contacts in the future.

A 'ContactList' object, should contain not only an array that is the list of contacts, but it would also contain the text label to put on the tab. So, it is more appropriate that the ContactList be more than a simple array, but rather it should be an object that contains an array as well as a text label.

The business logic is the following:

Contact name bgcolor lgcolor email

ContactTabs Employees Friends

     // class definition 
class Contact{ 
    // define properties 
    public $name; 
    public $bgcolor; 
    public $lgcolor; 
    public $email; 

    // constructor 
   public function __construct() { 

    } 

  //destructor 
  public function __destruct() { 

   } 

}

class ContactList extends Contact { 


    // constructor 
    public function __construct($contactname,$contactbgcolor,$contactlgcolor,$contactemail) {

 $this ->name = $contactname; 
 $this ->bgcolor = $contactbgcolor; 
 $this ->lgcolor = $contactlgcolor;
 $this ->email = $contactemail;  

    parent::__construct();
  }

  }

$johndie = new ContactList('John Die','#FCEDC9','#FEF9ED','somecontact1@g开发者_Python百科mail.com','9');

$johndoe = new ContactList('John Doe ','#DEEDFE','#EDF5FE','somecontact2@hotmail.com,'6');


$Friends = new ExtendedArrayObject($jp);
$Employees = new ExtendedArrayObject($elvete);

$ContactTabs= new ExtendedArrayObject($Employees,$Friends);

print_r($ContactTabs);


You had the Contact class correct (although you may want to use private/protected properties for encapsulation, but you can change that later).

This is how I would do it:

class Contact{ 
    public $name; 
    public $bgcolor; 
    public $lgcolor; 
    public $email;

    public function __construct($name, $bgcolor, $lgcolor, $email) {
        $this->name = $name;
        $this->bgcolor = $bgcolor;
        $this->lgcolor = $lgcolor;
        $this->email = $email;
    }
}

class ContactList implements Iterator, ArrayAccess {
    protected $_label;
    protected $_contacts = array();

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

    public function getLabel() {
        return $this->label;
    }

    public function addContact(Contact $contact) {
        $this->_contacts[] = $contact;
    }

    public function current() {
        return current($this->_contacts);
    }

    public function key() {
        return key($this->_contacts);
    }

    public function next() {
        return next($this->_contacts);
    }

    public function rewind() {
        return reset($this->_contacts);
    }

    public function valid() {
        return current($this->_contacts);
    }

    public function offsetGet($offset) {
        return $this->_contacts[$offset];
    }

    public function offsetSet($offset, $data) {
        if (!$data instanceof Contact)
            throw new InvalidArgumentException('Only Contact objects allowed in a ContactList');

        if ($offset == '') {
            $this->_contacts[] = $data;
        } else {
            $this->_contacts[$offset] = $data;
        }
    }

    public function offsetUnset($offset) {
        unset($this->_contacts[$offset]);
    }

    public function offsetExists($offset) {
        return isset($this->_contacts[$offset]);
    }
}

And ContactTabs would be very similar to ContactList, but would accept ContactList objects instead of Contact.

How it would work is:

// create some contacts
$bob = new Contact('Bob', 'black', 'white', 'bob@bob.com');
$john = new Contact('John', 'black', 'white', 'john@john.com');

// create a contact list and add contacts to it
$contactlist = new ContactList('Contacts');
$contactlist->addContact($bob);  // using a method
$contactlist[] = $john; // using array notation

// access the list by using foreach on it, since ContactList implements Iterator
foreach ($contactlist as $contact) {
     echo $contact->email;
}


First step will be to throw out all that code and start fresh. I don't know what "ExtendArrayObject" is, but you don't need it for this - it only complicates things. The rest of the code is not really on the right track.

In OOP, a class is supposed to model "something." Some kind of entity, which is often, but not always, a real-world thing. The first step in OO development is to sketch out the entities involved and model them in classes. In this case, your assignment tells you exactly what the entities are:

  1. Contact
  2. ContactList

So, OK, what do we need to know about our contact - what properties do we need it to have? Let's say "name" and "email." Let's give it these properties then:

class Contact {
    public $name;
    public $email;
}

A ContactList sounds pretty simple, it's just a list of Contacts, with a title that can be displayed in a tab. I'll write it so that it stores its Contacts internally in an array:

class ContactList {
    public $title;
    public $contacts = array();
}

You may be wondering, why do I need a ContactList if all it does is hold a title and store Contacts in an array? The answer is, because your assignment says you need it. :) Like many aspects of OOP, their usefulness will only be revealed as your projects increase in complexity. Just go along with it for now.

Now, put these classes in 2 separate files: Contact.php and ContactList.php. (This is not strictly necessary but is generally considered best practice.) Create a 3rd file called whatever, and in it, add the following code to tie it all together:

include("Contact.php");
include("ContactList.php");

// create a Contact object
$contact = new Contact();
$contact->name = "Bill";
$contact->email = "bill@gmail.com";

// create a ContactList object
$contact_list = new ContactList();
// set its title
$contact_list->title = "My Great Contacts";
// add our contact to it
$contact_list->contacts[] = $contact;

print_r($contact_list);

With this code, you are 80% of the way there - I didn't want to do exactly what your assignment specified because that would leave nothing left for you! I encourage you to play around with this until you feel like you really "get it." It often takes a while for OOP to "click" in one's head. But it's really crucial.

Exercises:

  • Add some different properties to the Contact class, like "phone" and "address"
  • Create some more contacts and add them to the list
  • Create a second ContactList object, containing a different list, with different contacts in it
  • Extra credit: Write a method in ContactList that adds a Contact, but only if another one with the same email address doesn't already exist in the list.
0

精彩评论

暂无评论...
验证码 换一张
取 消