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
<?php
class demo
{
var $first=1000;
var $second=500;
function add( )
{
$add=$this->first + $this->second;
echo "addition=".$add."<br/>";
}
function sub( )
{
$sub=$this->first - $this->second;
echo "subtraction=".$sub;
}
}
$obj= new demo();
$obj->add();
$obj->sub();
?>
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
<?php
class demo
{
var $first=1000;
var $second=500;
function add( )
{
$add=$this->first + $this->second;
echo "Addition=".$add."<br/>";
}
function sub( )
{
$sub=$this->first - $this->second;
echo "Subtraction=".$sub."<br/>";
}
function summary()
{
$this->add( );
$this->sub( );
$res=$this->first*$this->second;
echo "Multiplication=".$res;
}
}
$obj= new demo();
$obj->summary();
?>
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.