Search code examples
phpclassoopthis

What does the variable $this mean in PHP?


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?


Solution

  • 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.