PHP $this class - php tutorial for beginners - Phptpoint.com

PHP $this class

/ins>

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
addition=1500
subtraction=500

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
Addition=1500
subtraction=500
Multiplication=500000

In the above example
Create a class demo with two properties $first and $second, three methods add( ), subtract( ) and summary( ). Use the current class property $first and $second, inside add( ) and sub( ) method make calculation and store the result inside $add and $sub variable.

Now Inside summary( ) method call the current class property $first and $second for multiplication, and print the result with the help of echo statement.

Inside summary( ) method, call current class add( ) and sub( ) method using $this.
after closing of class demo body, create object of demo class and store the object reference in $obj variable.

call summary( ) method, with the help of connecter(connect class object with class method) and output will display addition, subtraction, and multiplication.