OOP PHP: What is the Double Colon in Objects/Classes for?

phpI happen to be the only PHP programmer that I know, so it’s hard to ask your buddy what the heck that :: is used for in some OO PHP programs.  I know you could post it on a forum and get the answer, but I never did.  And Google wasn’t really forth coming when you put :: in a search.  Finally I found it in the PHP documentation:  check out Scope Resolution Operator (::).  In short, it’s used to access Static or Constant members of a class.  Here’s a brief example:

 class DatabaseConnector {
   const CONNECTION_STRING = 'myconnectionstring';
}

//Referece that connection string constant like so...
DatabaseConnector::CONNECTION_STRING;

So there you go, mystery solved ;-)

In case you’re wondering what the :: is called, it’s a Paamayim Nekudotayim, which is Hebrew for the cryptic phrase: double colon!

Cheers,
Byron

Popularity: 14%

Tags: ,
Filed under: PHP

Comments

  1. beanluc Says:

    Does it do something that “->” doesn’t do?

    Under what circumstancces do you use “::” but NOT “->”?

    Under what circumstances will either one of them work? With ot without the same result?

  2. Byron Bennett Says:

    Hi beanluc,

    Sounds like a test question ;-)

    To use “::”, you need to be accessing static functions or variables, constants, or overridden functions. For a function, you’d need something like:

    public static function showAge(){…}

    then you could access it like: ClassName::showAge();

    When you’re working with an instance of an object, you use ->. In general, you’ll get the same results since you’re mostly working with Constants and static functions and they don’t usually change.

    Check out the link in the article above for a more details.
    Cheers!
    Byron

  3. Monkey Says:

    Thanks Byron,

    I do have people I could have asked… but I was too embarassed as I should have found this out a long time ago :-D

    At least now Googling the answer works… thanks to you :-D

  4. Byron Bennett Says:

    Monkey,

    I hear ya! Glad to help!

    Byron

  5. Daniel Says:

    HA! Finally, a good and simple answer! Indeed, I have had such trouble googling “::”. I don’t know why, but something about giving Google a bunch of symbols doesn’t give very good search results.

    Thanks for answering this question, it will come in very handy now that I know what the darn thing is and how to use it! I’ve actually asked people before, but when I ask about “that double colon thingy” I either got blank stares, or some over-technical jabbering that I could not understand.

    Thanks for the great post!

  6. Farhan Says:

    Thanks :)

  7. Mario Says:

    thanks for posting this. i was wondering too.

  8. yaniv Says:

    lol, I can speak hebrew so I know the paamayim nekudotaiim thingy, and thanks to you I can use it now :)
    thanks!

Leave a Reply