This method retrieves the phone number associated with a given $name. If the contact does not exist, it returns null.
Question: Why is returning null useful when a contact doesn't exist?
Answer: Returning null indicates that the contact was not found in the address book, enabling us to handle such cases clearly and allowing the code to make decisions based on the presence or absence of a contact.
Here is the method implementation:
<?php
class AddressBook {
private $contacts = array();
public function addContact($name, $phoneNumber) {
if (isset($this->contacts[$name])) {
return false;
}
$this->contacts[$name] = $phoneNumber;
return true;
}
public function getContact($name) {
if (isset($this->contacts[$name])) {
return $this->contacts[$name];
}
return null;
}
public function printContacts() {
foreach ($this->contacts as $name => $phoneNumber) {
echo "$name: $phoneNumber\n";
}
}
}
// Example usage:
$addressBook = new AddressBook();
$addressBook->addContact("Alice", "123-456-7890");
$contact = $addressBook->getContact("Alice");
if ($contact !== null) {
echo $contact . "\n"; // 123-456-7890
} else {
echo "Contact not found\n";
}
$contact = $addressBook->getContact("Bob");
if ($contact !== null) {
echo $contact . "\n";
} else {
echo "Contact not found\n"; // Contact not found
}
In this method:
- We check if the contact exists in the associative array using
isset.
- If the name exists, we return the phone number.
- If the name doesn't exist, we return
null.