【问题标题】:OOP: a->user->chk and a->pwd->chk in PHP? How can I define? [duplicate]OOP:PHP 中的 a->user->chk 和 a->pwd->chk?我该如何定义? [复制]
【发布时间】:2011-10-02 15:09:33
【问题描述】:

可能重复:
PHP method chaining?

我有一个创建用户的功能,例如类内的 cruser 并设置密码,例如 setpw

我想创建一个验证函数来检查用户名和密码,我想像这样使用它:

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

需要 2 个不同的功能或相同的功能吗? 太优雅了,怎么定义呢?

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

适用于 PHP 5.2/5.3。

我怎样才能做到这一点,或者有更好的方法吗?

【问题讨论】:

  • 您的密码/用户名检查应该由不同的类/服务完成。
  • 我相信$a->foo->bar() 被称为方法链接,可以通过从每个可链接方法返回$this 来实现。不过,我对细节有点粗略。
  • Ruchard H:不,我想在同一类中创建。我展示了用于测试的 phpunit 示例,但我想知道如何定义它。有可能是100%。问题是:如何? :)
  • Ross:如果我调用 $a->cruser->chk 和 $a->setpw-,如果你想检查 cruser 值和 setpw 值,你能输入一个如何定义 chk() 的小例子吗? >chk?如何检测 chk 内部调用此 chk() 的函数?
  • bazmegakapa:这不是重复,因为我有确切的例子需要解决。 :) 但也感谢您的帮助! :)

标签: php oop class


【解决方案1】:

这称为方法链接。您的方法需要返回被调用对象的实例。

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
    }
}

要设置用户名和密码并进行验证,您可以这样调用:

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

【讨论】:

  • 不要回复重复的。
猜你喜欢
  • 1970-01-01
  • 2021-08-15
  • 2023-02-13
  • 2014-07-28
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 2017-01-30
  • 2017-12-24
相关资源
最近更新 更多