Home > OS >  implementation of User class by using object
implementation of User class by using object

Time:03-26

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('[email protected]');
echo $user;

and i want the output like the following

   "John Doe <[email protected]>"

Following is what i am trying to do

  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;

}
}

CodePudding user response:

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);
}
  •  Tags:  
  • php
  • Related