Search code examples
phpoopclassthisself

Diffrences of $this:: and $this-> in php


Possible Duplicate:
PHP: self vs. $this

I've found that I can call class methods by $this:: prefix. example:

class class1 {
    public function foo()
    {
        echo "1";
    }
    public function bar()
    {
        $this::foo();
        //in this example it acts like $this->foo() and displays "2"
        //using self::foo() displays "1"
    }
}

class class2 {
    public function foo()
    {
        echo "2";
    }
    public function bar()
    {
        class1::bar();
    }
}

$obj = new class2();
$obj->bar(); // displays "2"
class1::bar(); // Fatal error

I want to know whats the diffrence of calling method with $this-> and $this:: prefixes.

ps: There is a page about diffrence of $this->foo() and self::foo() in this link: When to use self over $this?


Solution

  • The answer that you linked tells you exactly what you're looking for ;).

    Basically, there are two concepts that some people have a tough time differentiating in programming languages: objects and classes.

    A class is abstract. It defines a structure of an object. The properties and methods that an object would contain, if an object were built from that class. Creating an object is what you do when you call new class1(). This is instructing PHP to create a new object with all of the properties and methods on the class1 class.

    The important thing to note about creating an object is that it also has its own scope. This is really where $this vs static:: (note: do not use self:: or $this::, please use static:: (more on this later)) come in to play. Using $this is instructing PHP to access the properties and methods of your current object. Using static:: is instructing PHP to access the properties and methods of the base class that your object is constructed from.

    Here's an example:

    class MyClass {
        public $greeting;
        public static $name;
    
        public greet() {
            print $this->greeting . " " . static::$name;
        }
    }
    
    $instance1 = new MyClass();
    $instance1->greeting = 'hello';
    
    $instance2 = new MyClass();
    $instance2->greeting = 'hi';
    
    MyClass::$name = 'Mahoor13';
    
    $instance1->greet();
    $instance2->greet();
    

    I didn't test the above, but you should get:

    hello Mahoor13 hi Mahoor13

    That should give to a general idea of the difference between setting a class property and setting an instance property. Let me know if you need additional help.

    Edit

    $this:: appears to just be a side effect of the way that PHP handles scopes. I would not consider it valid, and I wouldn't use it. It doesn't appear to be supported in any way.