PHP $this class - php tutorial for beginners -

PHP $this class

PHP Summer Training/Internship with 2 Live Projects in Noida Fee is only 5500/-Click here to Book Your Seat


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


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


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.

Latest Trending Technologies