PHP5 $this variable

Advertisement

Anybody’s think and wonder what $this variable means in PHP, will $this variable is a pointer to the object making the function call. $this variable is not available in static methods. In this post, you will know how $this variable important, especially in PHP OOP.

Here is the sample:


<?php
class ryscript {

   private $name;

   public function DisplayName($name) {
	$this->name = $name;
   }
}

$rys1 = new ryscript();
$rys2 = new ryscript();

$rys1->DisplayName("ryan");
$rys2->DisplayName("sutana");
?>

In the above example, $rys1 and $rys2 are two separate ryscript objects. Each object has its own memory to store names. But if you see the function DisplayName() is common. During run time, how can it make a difference as to which memory location to use to store the function values? Therefore, it uses the $this variable. As mentioned earlier, $this variable is a pointer to the object making a function call.

Therefore when we execute $rys1->DisplayName("ryan"), $this in the DisplayName() function is a pointer or a reference to the $rys1 variable.

Hope this post will help you in your PHP project or school web project.

Advertisement