Use $this
when accessing class variables.
When referring to a variable, which is actually a parameter in a function, there is no need to use the $this
. In fact, to access a function parameter with $ params parameters, you should not use $ this keyword ...
In your example:
class TestClass{ public function TestFunc($params){ $this->params = $params; echo 'testing this something'. $this->params; } }
$params
from TestFunc($params){
is a parameter / argument of the TestFunc
function, so you do not need to use $this
. In fact, to access the parameter value, you should not use $this
- now that you have used $this->params
from $this->params = $params = $params;
, you actually set the value equivalent to the value of the $params
parameter to a NEW class- level variable with the name also $params
(since you did not declare it anywhere in your code example)
[edit] based on the comment:
Take a look at this example:
class TestClass{ public function TestFunc($params){ $this->params = $params;
The error when calling EchoParameterFromFunction_TestFunc
without first calling TestFunc
is the result of not declaring / setting a class variable / property with the name $params
- you specified this inside TestFunc
, which means that it is not set unless you call TestFunc
. To install it correctly so that everyone can immediately access it:
class TestClass{ # declare (and set if you like) public $params;
[edit: optional]
As @liquorvicar , which I also totally agree on, is that you should always declare all your class level properties / variables, regardless of whether you will use them. The reason is that you do not want to access a variable that has not been set. See my example above, which triggered an undefined property TestClass::$params
error undefined property TestClass::$params
..
Thanks @liquorvicar for reminding me.