$this keyword used for?

Discussion in 'PHP' started by bhuppi890109, Apr 27, 2011.

  1. #1
    hi friends.. i want to know that why we use $this-> keyword in classes of php.. and how to use this ...and when we should use it..
    thanks in advance
     
    bhuppi890109, Apr 27, 2011 IP
  2. ap2010

    ap2010 Guest

    Messages:
    41
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Inside the code of a class, you can use the this to refer to the object itself.

    
    <?php
    	class Foo
    	{
    		public $Bar;
    		public function __construct()
    		{
    			$this->Bar = 0;
    		}
    		public function Baz()
    		{
    			$this->Bar = 10;
    		}
    	}
    	$foo1 = new Foo();
    	$foo2 = new Foo();
    	$foo1->Baz();	// sets the value of $Bar inside $foo1 to 10
    					// does not affect the $Bar inside $foo2
    	var_dump($foo1, $foo2);
    ?>
    
    PHP:
     
    ap2010, Apr 28, 2011 IP
  3. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #3
    It's how you access properties and methods within the same class. The scope of "$this->" extends only within the class or its children.
     
    jestep, Apr 28, 2011 IP
  4. Mak3MyDay

    Mak3MyDay Peon

    Messages:
    25
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Another example is:

    class Foo{
    public $Bar;
    public Set_Bar($Bar){
    $this->Bar = $Bar;
    }
    }
     
    Mak3MyDay, Apr 29, 2011 IP