Use of $this class in PHP
- To access or change a class method or property within the class itself, it’s necessary to prefix the corresponding method or property name with “$this” which refers to this class.
Access current class properties inside current class method
Output:
In the above example
- Create a class demo with two global properties $first hold 1000 and $second hold 500.
- Now want to access these class properties inside class method add( ) and sub( ).
- So inside add( ) method call these class properties( to prefix the corresponding property name with “$this”) with the help of “$this”, store the result inside $add variable.
- Print the $add variable using echo statement.
- Do the same for sub( ) method and store the result in $sub variable.
- Now create the object of demo class, using “new” keyword and store the object reference in $obj variable.
- call the method add( ) and sub( ) with the help of object(using connector(->) ).
Access current class methods inside other method
Output: