Hi
people of the bandwidth world!!!
Hey guys How are you today?

What does $THIS-> actually do?

I'm advancing in OOP programming using PHP....
Please enlighten me on this or if you have resources that
explains all this in "ENGLISH"

Thanks Guys

Recommended Answers

All 2 Replies

Hi.

Here is an example :

<?
    class dummy {
        var $variable;
        var $variable2 = 1;
        var $variable3 = 2;
        function sum($one, $two) {
            $val = $one + $two;
            return $val;
        }
        function sum2() {
            $val = $this->sum($this->variable2, $this->variable3);
            return $val;
        }
    }
?>

The "$this" variable is a reserved variable in object-oriented PHP programming (translation - don't use it in your classes!) that actually does the inheritance. "$this->sum()" is basically interpreted as, "in this class, perform the sum() function." Like "$this->sum()", "$this->variable2" is interpreted as "in this class, use the value of 'variable2'." Likewise with $this->variable3. Note: all calls to native class functions or variables are done in this manner. Starting with "$this->" and followed by the name of the function or variable you wish to use. I can't stress the importance of that enough.

http://www.spoono.com/php/tutorials/tutorial.php?id=27


- Mitko Kostov

$this->

is reffering to the current class instance.
it allows you to differentiate between objects and can help speed up compile time as the compiler knows that $this-> is referencing an object in the document

e.g.

var $num1;

function set_num($num1)
    {
        $this->num1= $num1;
    }

not only does it help the compiler but it helps visually as you can see where its exactly pointing to.

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.