I'm having trouble understanding the keyword 'this' in php. When and where does it need to be used? Why can you not simply use the variable name as you would normally do when not placing a variable inside a class? In the small test case program below I can't even get the 'this' keyword to work.

#!/usr/bin/php5

<?php

class A
{
    public $attribute = 'first attribute';

    function myFunction()
    {
        echo "This is my attribute without the keyword this --> $attribute";
        echo "This is my attribute with the keyword this --> $this->$attribute";
    }
}

$a = new A();
$a->myFunction();

?>
Member Avatar for diafol

$this helps you access all the class's functions (methods) and variables (properties). In a way it makes the variables 'global' to all methods within the class. It also differentiates between these class variables - which can be public/protected or private and any ad hoc variables you may have just within the method itself.

 function myFunction()
    {
        echo "This is my attribute without the keyword " . $this->attribute;
        echo "This is my attribute with the keyword this --> " . $this->attribute;
    }

You can't just place the $this->var in a string, it like an array var item, you can brace it out:

   echo "This is my attribute without the keyword {$this->attribute}";

Note that you always place the '$' in front of 'this'. If you have a $ on the property name too, then php will look for a property like this:

private $me = 'you';
private $you = 'other';

echo $this->me; //you
echo $this->$me //other

The 'visibility' of a property (as opposed to a standard variable in a method) ensures that child classes can inherit the property or it may be gettable/settable by the client. Look up visiblity, inheritance and encapsulation.

An example, with you class A (just try to execute it, might clear things up a bit more for you):

<?php
class A
{
    private $private_attribute = 'this is a class attribute, that you can use in any of this class\'s functions';
    public $public_attribute = 'this is a class attribute, that you can use in any of this class\'s functions AND even outside of the class';

    function myFunction()
    {
        $attribute = 'this is an attribute bound to this function; not to this class';

        echo $attribute . '<br>';
        echo $this->private_attribute . '<br>';
        echo $this->public_attribute . '<br>';
    }
}

$class = new A();
$class->myFunction();

// Let's see what happens now:
echo $class->public_attribute . '<br>';
echo $class->private_attribute . '<br>';
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.