Super easy question. Look at the 2 sample class methods.
In the first One I pass in a variable/property call $params I then do $this->params
My question is, is it really needed, I generally do it this way but I have noticed that it will work in the second example with just calling $params without setting $this to it.
So my theory is this… You have to set it like $this->params if you need to access that property in a different method in that class and you can use just $params if you are only using that property in that same method it is in already.
Could somebody shed some light on this and explain if my theory is correct or if I am way off I would like to know the reasoning for this so I will know when do do each method or to do one or the other all the time, thanks you
class TestClass{
public function TestFunc($params){
$this->params = $params;
echo 'testing this something'. $this->params;
}
}
without defining variables
class TestClass2{
public function TestFunc2($params){
echo 'testing this something'. $params;
}
}
Use
$thiswhen accessing class variables.When accessing a variable which is actually a parameter in a function, there’s no need to utilize the
$thiskeyword.. Actually, to access the function parameter named $params, you should not use the $this keyword…In your example:
$paramsfromTestFunc($params){is a parameter/argument of the functionTestFuncand so you don’t need to use$this. In fact, to access the parameter’s value, you must not use$this— Now when you used$this->paramsfrom$this->params = $params = $params;, you are actually setting a value equivalent to that of the parameter$paramsto a NEW class-level variable named also$params(since you didn’t declare it anywhere in your sample code)[edit] based on comment:
Look at this example:
The error when you called
EchoParameterFromFunction_TestFuncwithout first callingTestFuncis a result of not declaring/setting the class-level variable/property named$params–you set this up insideTestFunc, which means it doesn’t get set unless you callTestFunc. To set it right so that anyone can immediately access it is to:[edit : additional]
As @liquorvicar mentioned, which I also totally agree with is that you should always declare all your class-level properties/variables, regardless of whether or not you will use them. Reason being and as an example is that you don’t want to access a variable that hasn’t been set. See my example above which threw the error
undefined property TestClass::$params..Thanks to @liquorvicar for reminding me..