I am new to PHP and have been struggling with echoing out a first name, last name, and email address as objects inside of a foreach loop. I have used a Profile.php class to define those and the get and set methods, and then I have a User.php class to set up a Username and Profile object and its get and set methods. I don't use the username object at all for my answer, according to people I have tried getting help from. I believe that the problem is within the foreach loop in index.php, but I have worked for hours and cannot wrap my head around it yet. Here is the UML for the program.
Here is what the program should ouput.
And here is the code itself:
index.php:
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- </head>
- <body>
-
- <?php
-
- require_once('User.php');
- require_once('Profile.php');
-
- $professors = array("Andrew Besmer", "Gerry Derksen");
-
- $andrewUser = new User();
- $andrew = new Profile();
-
- $andrewUser->setProfile($andrew);
-
- $andrew->setFirstName("Andrew");
- $andrew->setLastName("Besmer");
- $andrew->setEmailAddress("besmera@fakeemail.com");
-
- $gerryUser = new User();
- $gerry = new Profile();
-
- $gerryUser->setProfile($gerry);
-
- $gerry->setFirstName("Gerry");
- $gerry->setLastName("Derksen");
- $gerry->setEmailAddress("derkseng@fakeemail.com");
-
- foreach($professors as $profile) {
- echo "<h2>" . $profile . "</h2>";
- echo "<ul>";
- echo "<li><b>First:</b>" . $profile->getFirstName() . "</li>";
- echo "<li><b>Last:</b>" . $profile->getLastName() . "</li>";
- echo "<li><b>Email:</b>" . $profile->getEmailAddress() . "</li>";
- echo "</ul>";
- }
- echo "<br>";
- ?>
-
- </body>
- </html>
Profile.php:
- <?php
- class Profile {
- protected $firstName = "";
- protected $lastName = "";
- protected $emailAddress = "";
-
- public function __construct(){
-
- }
-
- public function getFirstName(){
- return $this->firstName;
- }
-
- public function setFirstName($firstName){
- $this->firstName = $firstName;
- }
-
- public function getLastName() {
- return $this->lastName;
- }
-
- public function setLastName($lastName) {
- $this->lastName = $lastName;
- }
-
- public function getEmailAddress() {
- return $this->emailAddress;
- }
-
- public function setEmailAddress($emailAddress) {
- $this->emailAddress = $emailAddress;
- }
- }
- ?>
User.php:
- class User {
-
- protected $username = "";
- protected $professors = array();
-
- public function __construct(){
-
- }
-
- public function getUsername(){
- return $this->username;
- }
-
- public function setUsername($username) {
- $this->username = $username;
- }
-
- public function getProfile(){
- return $this->profile;
- }
-
- public function setProfile($profile){
- $this->profile = $profile;
- }
- }
Thanks for the help and your time.