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();
精彩评论