Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

implementation of User class by using object

i am new to php and i want to achieve the following. i have search on internet but i didnt find any help.

$user = new User();
$user->setFirstName('John')->setLastName('Doe')->setEmail('john.doe@example.com');
echo $user;

and i want the output like the following

   "John Doe <john.doe@example.com>"

Following is what i am trying to do

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  class User {
  // Properties
  public $setFirstName;
  public $setLastName;
  public $setEmail;

// Methods

function setFirstName($setFirstName) {
$this->setFirstName = $setFirstName;
}

   function setLastName($setLastName) {
$this->setLastName = $setLastName;
   }

   function setEmail($setEmail) {
     $this->setEmail = $setEmail;

}
}

>Solution :

If you want to be able to chain multiple method calls like this:

$user->setFirstName('John')->setLastName('Doe')...

Then you simply need to have each of your setter methods return the special self-referencing object variable $this:

function setFirstName($setFirstName) {
    $this->setFirstName = $setFirstName;
    return $this;
}

If you want echo $user; to display something meaningful, you can implement the __toString magic method. Have it return whatever string you want to display:

function __toString() {
    return sprintf('%s %s <%s>', $this->setFirstName, $this->setLastName, $this->setEmail);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading