我们如何在类php上设置许多设置器

时间:2019-01-08 19:25:37

标签: php

我试图在我的php代码上获得此结果,我需要实现

class person 

    $person = new person();

    $person->setFirstName('name')
        ->setLastName('lastname')
        ->setEmail('email@example.com')
    ;

    echo $user;

然后我得到这个结果   将产生一个字符串

“姓氏”

这是我的类实现的示例,但没有用,我需要实现三个设置器setFirstName,setLastName,setEmail才能在上面得到我的结果代码。

class User {
  private $FirstName;
  private $LastName;
  private $Email;
    public function getFirstName() {
        return $this->FirstName;
    }

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

    public function getLastName() {
        return $this->LastName;
    }

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

    public function getEmail() {
        return $this->Email;
    }

    public function setEmail($x ) {
        $this->Email = $x;
    }
}

2 个答案:

答案 0 :(得分:2)

您的问题很难理解。无论如何,此代码将为您提供一个类Person并对其进行测试。 输出:“姓氏

代码:

    class Person
    {
        private $firstname, $lastname, $email;

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

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

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

        function __toString() {
            return $this->firstname. ' ' .$this->lastname. ' <' . $this->email .'>';
        }
    }

    $person = new Person();

    $person->setFirstName('name')
        ->setLastName('lastname')
        ->setEmail('email@example.com');

    echo $person;

希望这是您搜索的内容! <我想你所需要的是>和&lt;

答案 1 :(得分:1)

如果我正确理解了您的答案,则需要执行以下操作:

echo $person->getFirstName() . ' ' . $person->getLastName() . ' ' . $person->getEmail();

结果::Samir Guiderk Samir@example.com>