开发者

OOP: a->user->chk and a->pwd->chk in PHP? How can I define? [duplicate]

开发者 https://www.devze.com 2023-03-19 03:03 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: PHP method chaining? I had a function for create user, like cruser inside class and set password like setpw
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

PHP method chaining?

I had a function for create user, like cruser inside class and set password like setpw.

I want to create a validate function to check the username and password and I want use it like this:

$a = new class abc();
$a->cruser->chk();
$a->setpw->chk();

开发者_如何学运维Need 2 different function or same can do? It's so elegant, how can I define this?

class abc {
    function cruser { }
    function setpw {}
    //??? - need to define here chk or to different class?
}

for PHP 5.2/5.3.

How can I achieve this, or is there a better way?


This is called method chaining. Your methods need to return the instance of the object being called.

class abc {
    protected $_username;
    protected $_password;
    public function cruser($username)
    {
        // Run your CREATE USER code here...
        // e.g., $this->_username = $username;
        return $this;
    }
    public function setpw($password)
    {
        // Run your SET PASSWORD code here...
        // e.g., $this->_password = $password;
        return $this;
    }
    public function validate()
    {
        // Validate your user / password here by manipulating $this->_username and $this->_password
    }
}

To set a username and password and validate, you'd call like this:

$a = new abc;
$a->cruser('user')->setpw('pass')->validate();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号