将本地属性/变量传递给该类中的函数/方法?

时间:2011-11-30 02:22:18

标签: php oop class

我是OOP的新手,所以这可能是一个非常天真的问题;但每当我尝试使用$this->var语法将类局部变量传递到该类中的函数时,它会在我的IDE(NetBeans)中标记语法错误。

我已尝试将其包含在括号中({$this->var}$this->{var}),但似乎都无效。

这是我的代码:

class password_class {
    public $stretch = 1;
    public $salt = 'DEFINE_SALT';
    public $algo = 'sha256';

    function create_salt() {
        $this->salt = md5(rand()).uniqid();
    }

    function hash_pass($pass, $this->algo, $this->salt, $this->stretch) {

    }
}

我实际上并不打算将其用于密码安全措施;看到类变量/函数的使用更多的是测试(这将是我第一次创建和调用我自己的类)。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

如果使用实例属性,则在OOP中,您不需要将它们作为参数传递。事实上,如果你想使用$this->algo等等,你可以这样做:

function hash_pass($pass) {
   // example statement
   $var = hash($this->algo, $this->salt . $pass);
}

此外,如果你需要参数,你可以这样做:

function hash_pass($pass, $algo = null, $salt = null, $stretch = null) {
   if ($salt === null)
      $salt = $this->salt;

   // other if like this
   // example statement
   $var = hash($algo, $salt . $pass);
}

答案 1 :(得分:2)

您无法将默认方法/函数参数设置为对象的字段。你必须重写它:

function hash_pass($pass, $algo = null, $salt = null, $stretch = null) {
    $alog    = $algo == null ? $this->algo : $algo;
    $salt    = $salt == null ? $this->salt : $salt;
    $stretch = $stretch == null ? $this->stretch : $stretch;
}

作为@Aurelio De Rosa pointed out,您不必将实例变量传递给方法;他们已经在你身边了。

相关问题