何时在PHP中使用$ this-> property而不是$ property

Jas*_*vis 4 php oop

超级简单的问题.看看2个样本类方法.

在第一个我传入变量/属性调用$params然后我做$this->params

我的问题是,它是否真的需要,我通常这样做,但我注意到它将在第二个例子中工作,只需调用$params 而不设置$this它.

所以我的理论就是这样...... $this->params如果你需要在该类中的另一个方法中访问该属性,你必须设置它,如果你只是$params在同一个方法中使用该属性就可以使用它.

有人可以对此有所了解并解释我的理论是否正确或者我是否离开了我想知道这个的原因所以我会知道什么时候做每种方法或者一直做一个或者另一个,谢谢您

class TestClass{

    public function TestFunc($params){
       $this->params = $params;

       echo 'testing this something'. $this->params;
    }
}
Run Code Online (Sandbox Code Playgroud)

没有定义变量

class TestClass2{

    public function TestFunc2($params){
       echo 'testing this something'. $params;
    }
}
Run Code Online (Sandbox Code Playgroud)

Non*_*nym 9

使用$this访问类变量时.

当访问实际上是函数中的参数的变量时,不需要使用$this关键字.实际上,要访问名为$ params的函数参数,您不应该使用$ this关键字...

在你的例子中:

class TestClass{

    public function TestFunc($params){
       $this->params = $params;

       echo 'testing this something'. $this->params;
    }
}
Run Code Online (Sandbox Code Playgroud)

$paramsfrom TestFunc($params){是函数的参数/参数,TestFunc因此您不需要使用$this.事实上,进入参数的值,你不能使用$this-当你使用现在$this->params$this->params = $params = $params;,你相当于该值在实际设置参数 $params来命名一个新的类级变量 $params(因为你没有把它声明示例代码中的任何位置)

[编辑]根据评论:

看看这个例子:

class TestClass{

    public function TestFunc($params){
       $this->params = $params;
       # ^ you are setting a new class-level variable $params
       # with the value passed to the function TestFunc 
       # also named $params

       echo 'testing this something'. $this->params;
    }

    public function EchoParameterFromFunction_TestFunc() {
        echo "\n\$this->params: " . $this->params . "\n";
        # now you are echo-ing the class-level variable named $params
        # from which its value was taken from the parameter passed
        # to function TestFunc
    }

}

$tc = new TestClass();
$tc->EchoParameterFromFunction_TestFunc(); # error: undefined property TestClass::$params
$tc->TestFunc('TestFuncParam');
$tc->EchoParameterFromFunction_TestFunc(); # should echo: $this->params: TestFuncParam
Run Code Online (Sandbox Code Playgroud)

EchoParameterFromFunction_TestFunc没有第一次调用的情况下调用时的错误TestFunc是未声明/设置名为的类级别变量/属性的结果 - $params你在里面设置它TestFunc,这意味着除非你调用它,否则它不会被设置TestFunc.要正确设置,以便任何人都可以立即访问它是:

class TestClass{
    # declare (and set if you like)
    public /*or private or protected*/ $params; // = ''; or create a construct...

    public function __construct(){
        # set (and first declare if you like)
        $this->params = 'default value';
    }
...
...
...
Run Code Online (Sandbox Code Playgroud)

[编辑:额外]

正如@liquorvicar所提到的那样,我也完全同意的是,无论是否使用它们,都应该始终声明所有类级属性/变量.原因是作为一个例子,您不想访问尚未设置的变量.请参阅上面的示例,该错误引发了错误undefined property TestClass::$params.

感谢@liquorvicar提醒我..