When to use $this correctly?

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
seandisanti
php-forum Fan User
php-forum Fan User
Posts: 973
Joined: Mon Oct 01, 2012 12:32 pm

Mon Feb 25, 2013 9:39 am

$this references the current instance of a class. it'll make a little more sense if you mix up your example code a bit, like so: (throwing in a use of self also to show you the difference)

Code: Select all

<?php

class SimpleClass {

    // property declaration
    public $var = "Initial Value";
    public static $classVar = "static variables are the same for all instances";

    // method declaration
    public function displayVar() {
        return $this->var."<br />";
    }

    public function setVar($value = '') {
        $this->var = $value;
    }
    
    public static function setStaticVar($value){
        self::$classVar=$value;
    }

}

$b = new SimpleClass();
$a = new SimpleClass();
echo 'a: ' . $a->displayVar();
echo 'b: ' . $b->displayVar();
$a->setVar('New value for a');
echo 'a: ' . $a->displayVar();
echo 'b: ' . $b->displayVar();
echo 'classVar: ' . SimpleClass::$classVar;
?>

I've modified your function so that it returns a value to be echoed instead of letting it echo on its own, and setup the examples at the bottom so that you get to see setting and viewing instance variables which can be changed for the individual instance by using $this, or static (class) variables that can be accessed with self:: or the class name. Does that help?

Post Reply
  • Information
  • Who is online

    Users browsing this forum: No registered users and 10 guests