Difference between "->" and "::" in PHP MySQLi OOP

John picture John · Aug 7, 2009 · Viewed 12.9k times · Source

Can anyone tell the difference between mysqli->commit and mysqli::commit?

The header in this page is mysqli::commit, but in examples they use mysqli->commit.

Answer

Andrew Moore picture Andrew Moore · Aug 7, 2009

-> is used when referring to a member of an object.

:: is the Scope Resolution Operator and is used to refer to a static member of a Class.

Consider the following class:

class FooBar {
    public static function fizz() {
        echo "Fizz";
    }

    public function buzz() {
        echo "Buzz";
    }
}

You would call the function buzz() using ->:

$myFooBar = new FooBar();
$myFooBar->buzz();

But would use :: to call the functon fizz(), as it is a static member (a member which doesn't require an instance of the class to be called):

FooBar::fizz();

Also, while we are talking about the difference between static members versus instantiated members, you cannot use $this to refer to the current instance within static members. You use self instead (no leading $) which refers to the current class, or parent if you want to refer to the parent class, or if you have the pleasure of working with PHP 5.3.0, static (which allows for late static binding).


The documentation uses :: to refer to a function inside a class as the class name in the header is not an instance of the class. Still using the same example, a documentation entry referring to the function buzz() would use the following header:

FooBar::buzz

But unless the documentation specifies it's a static member, you will need to use -> on an instance to call it:

$myFooBar = new FooBar();
$myFooBar->buzz();