-3

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?

Community
  • 1
  • 1
John
  • 13
  • 1
  • Your password/username checking should be done by a different class/service. – Richard H Jul 11 '11 at 08:59
  • I believe `$a->foo->bar()` is known as method chaining, and can be achieved by returning `$this` from each chain-able method. I'm a little sketchy on the specifics however. – Ross Jul 11 '11 at 09:00
  • Ruchard H: No, I want create in SAME CLASS THIS. I show phpunit example for tests, but I want know how I can define this. It's possible it's 100%. Question is: how? :) – John Jul 11 '11 at 09:05
  • Ross: can you type a little example how you define chk() if you want check cruser value and setpw values, if I call $a->cruser->chk and $a->setpw->chk? How can I detect inside of chk what function calling this chk() ? – John Jul 11 '11 at 09:07
  • bazmegakapa: it's not duplication because I had exact example what need to solve. :) But thanks your help too! :) – John Jul 11 '11 at 09:09

1 Answers1

2

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();
plasmid87
  • 1,450
  • 1
  • 14
  • 20