When to use $this correctly?

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

radulescuiulia
New php-forum User
New php-forum User
Posts: 2
Joined: Sat Feb 23, 2013 6:42 am

When to use $this correctly?

Postby radulescuiulia » Sat Feb 23, 2013 8:42 am

Hello!

I have another problem concerning classes. I've tried the following code, which prints "Class Examples":

Code: Select all

<?php
class SimpleClass
{
   
    // property declaration
    public $var = "Class Examples";

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}

$a = new SimpleClass();
$a -> displayVar();

?>


:help: I don't understand why it prints out "Class Examples" when I use echo $this-> var, but doesn't print anything when I simply use echo $var? :help:

I can't seem to understand when $this is necessary... Please help me out. :o

Thank you in advance! :D

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

Re: When to use $this correctly?

Postby seandisanti » 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?


Return to “PHP coding => General”

Who is online

Users browsing this forum: Google [Bot] and 1 guest