1

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;

}
}

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks alex. with me the problem was that i was not know the name of the this process now find the name and its method changing. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.