What does the variable $this mean in PHP?

waiwai933 picture waiwai933 · Oct 6, 2009 · Viewed 208.1k times · Source

I see the variable $this in PHP all the time and I have no idea what it's used for. I've never personally used it.

Can someone tell me how the variable $this works in PHP?

Answer

meder omuraliev picture meder omuraliev · Oct 6, 2009

It's a reference to the current object, it's most commonly used in object oriented code.

Example:

<?php
class Person {
    public $name;

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

$jack = new Person('Jack');
echo $jack->name;

This stores the 'Jack' string as a property of the object created.