PHP类成员和方法

nom*_*xpi 5 php oop class

我已经四处搜索但是在PHP类中使用$ this时找不到确定的答案(如果有的话).我仍然试图使用OOP方法来解决问题,并希望确保我使用最佳实践.

所以我的问题是你应该如何以及何时定义变量以及何时应该使用$ this来引用它们.

说我有以下课程....

class Foo {

private $pin;
private $stat;

public function get_stat($pin) {
            $this->stat = shell_exec("blah read $pin");
            return $this->stat;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以在上面的函数中,我将var $ pin传递给了class方法.这可以正常工作而不必使用$ this-> pin ...但是下面的代码看起来更像是正确的方法来做同样的事情.....

class Foo {

private $pin = 0;
private $stat = 0;

public function get_stat($pin) {
            $this->pin = $pin;
            $this->stat = shell_exec("blah read $this->pin");
            return $this->stat;
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,我已经将$ pin和$ stat变量设置为= 0.我认为这可以是一个默认值,或者我可以像第一个示例私有$ pin一样定义它们.和私人$ stat;.

回到我的问题,关于如何在类方法中使用成员和$ this的最佳实践是什么?每个例子的优点和缺点是什么?

Sve*_*ven 6

使用任何类成员时必须使用$ this.使用局部变量时,不得使用它.如果没有必要,您应该避免使用类成员,例如$this->pin在第二个示例中.