PHP operators: double and single arrow

Someone recently asked a question on the Professional PHP Programmers Google Group that I thought was interesting. This question interested me for a few reasons:

  1. The PHP manual is a very good manual and usually covers things like this; and,
  2. I remember asking this very question when I first started developing.

Hi all, I’m new to the mailing list, and new to php, and new on programming.

Here I go:

I have a question but I was unable to find an answer for this on the web. Because I have no Idea how to ask this on a search engine.

What’s the meaning of -> and => on php?

As good as the PHP manual is, and as well documented as the operators in PHP are, the documentation on these two operators is lacking severely. Even naming is horribly lacking for these two operators, as a recent Twitter chat shows:

More on the operators used in PHP can be found at http://us3.php.net/manual/en/language.operators.php. Unfortunately, these operators will not be found there. So to assist in explaining what these operators are and what they do, lets dig a little deeper in the world of cryptic symbols that remain unnamed in PHP. Shall we?

The double arrow operator, “=>”, is used as an access mechanism for arrays. This means that what is on the left side of it will have a corresponding value of what is on the right side of it in array context. This can be used to set values of any acceptable type into a corresponding index of an array. The index can be associative (string based) or numeric. So if I have an array like:

<?php
$myArray = array('Big', 'Small', 'Up', 'Down');
?>

Then in effect the code is saying:

<?php
$myArray = array(
  0 => 'Big',
  1 => 'Small',
  2 => 'Up',
  3 => 'Down'
);
?>

This is not a real surprise seeing as arrays in PHP are numerically indexed, zero-based arrays by default. But what if you wanted a hash of keys and values? Like when passing something as a form or in a querystring or reading results from a database? Well then, you would want to associate a key to a value in the array, or something like:

<?php
$myArray = array(
  'Robert' => 'Big',
  'Bobby' => 'Smart',
  'PHP' => 'Rocks'
);
?>

Now you have a hash of values assigned to indeces using the double arrow, or array value assignment, operator (“=>”).

The object operator, “->”, is used in object scope to access methods and properties of an object. It’s meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here. We’ll talk about that a little more in just a bit.

If you come from a background in object oriented programming then you know that every object has a way to access the methods and properties of the instantiated object. In most languages that is the dot operator (“.”). In PHP the dot operator has completely different meaning (it is used to concatenate strings) so don’t use that for object scope resolution. Instead, after instantiating an object, access its methods and properties using the object operator, like this:

<?php
$obj = new MyObject(); // Create a new instance of MyObject into $obj
$obj->thisProperty = 'Fred'; // Set a property in the $obj object called thisProperty
$obj->getProperty(); // Call a method of the $obj object named getProperty
?>

Now, getting back to object basics, remember I said that instantiated was a key term? The reason for that term is because there is another operator related to scope resolution than can be used but it is neither an arrow nor can it be used on objects. It can only be used on classes (this is as of PHP 5 – since PHP4 has already been fed to the dogs we are only going to talk about PHP 5). Class scope resolution is identified by the Paamayim Nekudotayim, or double colon, operator (“::”).

If you use a static class or static methods or properties within a class, you would not use the object operator (“->”) but would instead use the scope resolution, or double colon, operator, like so:

<?php
MyClass::$staticProperty = 'Fred'; // Sets a values into the static class
MyClass::getStaticProperty(); // Gets a value from a static method
?>

Now that you have the power of operators at your fingertips, even if in a very basic sense, you can get busy with assigning and accessing goodies in arrays, objects and classes. And remember as you use these that nothing at all can replace the learning you would get from trying them out, especially when you try to use them the wrong way (error messages can be quite educational).

If I could leave you with one bit of advice it would be to get your hands dirty on some of them and see what the parser tells you when it chokes on one (or more) of them.

And have fun. Stepping in to object oriented programming can be a frustrating, painful experience for some. But it is definitely a rewarding one.

33 Replies to “PHP operators: double and single arrow”

  1. A very good article and prolly the only one out there addressing this issue. When i first started with OOP i was having this exact question. Im sure this will be alot of help for new PHP OOP’ers 🙂

    cheers

  2. Great Article. Just getting into this junk now trying to write, or understand a script for authorize.net. This arrow operator was has to find just because I couldn’t figure out what to call it. Thanks for your simplified keywords in URL. Good SEO 😉

  3. I’m glad it was helpful. When I first started programming I saw both of the arrow operators and had no idea what they where. I had asked a question about the operators on the PHP Developer’s Network forum when I was first starting out and got lots of answers. It appears since then there have been several other people who have asked that question over there:

    DISCLAIMER: In the interest of full disclosure… as of now I am a long time administrator of the forums I link to above. When I posted my original question I was a new member. I am not trying to promote the forums, but I will stand by any assertions I may make to the notion that the PHP Developer’s Network forums are indeed one of the best PHP development resources around.

  4. As a designer moving into development, I found this article helpful, because it defines some concepts like the double arrow and object operators, definitions so fundamental that it seems like other tutorials and articles just gloss over them because it is assumed that they are already fully understood by readers. So, thank you for the detailed and very well-written educational article.

  5. Thanks so much! I figured it was something along those lines, but, as you stated, it’s impossible to search “=>”, so the error codes in the php output actually helped describe what “=>” or “double arrow” is actually called.

  6. And have fun. Stepping in to object oriented programming can be a frustrating, painful experience for some. But it is definitely a rewarding one.

    Helps me a lot. And definitely frustrating to switch from procedural mindset to object-oriented mindset.

  7. Hi Robert
    Thank you so much for starting this awesome forum and Yash, thanks so much for the link. I have found them to be very important.

    Cheers,
    Mo

  8. “the -> operator” is how I have always thought of it, understanding that it is specific to objects and having programmed before think of it “like a” pointer. That works for me. So “object operator” definitely works very well. I loved the back / forth discussion and I like your blog.

    To reinforce that answer with prior art, not that you can get any more “prior” than either @rasmus and the code itself, lol… Loved his answer.

    I pulled an old book off my shelf, Sams Teach Yourself PHP in 24 Hours, by Matt Zandstra as his explanations of OOP with PHP and the later chapters on writing your own MVC I found extremely helpful in the beginning.

    Zandstra, Matt. SAMS Teach Yourself PHP in 24 Hours, Third Edition. Indianapolis, Indiana: SAMs Publishing, 2004. (ISBN: 0-672-32619-1; Library of Congress Catalog Card Number: 2003109402.)exit

    Note the copy I had was the “third edition”, the first was released on December 2003 and he was referring to it as an operator specific to objects at that time.

    On p. 158 para 2, (Hour 9 Objects) Matt refers to it as “the -> operator” used to call “an object method”. In explanation he states that the reader at this point already knows how to access a property “from outside an object, but how does an object refer to itself?”

    That gets the noodle thinking, doesn’t it! I remember immediately thinking of “recursion” but I digress.

    Matt drives the point home in para 1 on p. 199 suggesting to think of it as a “personal pronoun”.

    He mentions that combing a “pseudo-variable and ->, you can access any property or method in a class from within the class itself.” That description and this next sentence drove it it home for me, so perhaps it will help others too.

    “A class uses the special variable $this to refer to the currently instantiated object (line 6)” ~ Matt Zandstra. I included Matt’s code example below.

    You can pick up a used copy of that book via Amazon for less than $5, I think I paid $2.50 + shipping, back in 2003-4 it was well worth the $24.99. I found it to be very helpful learning PHP back in the day, and his three hours on PHP OOP including his explanation of Model View Controllers (MVC) was very helpful. Next time you purchase anything, add it to your shopping cart and share the shipping, lol.

    Listing 9-3 Changing the Value of a Property from within a Method, Matt Zandstra.

    <?php
    class Item {
     var $name = "item";
     
     function setName ( $n ) {
       $this->name = $n;   
      }
     
      function getName () {
        return $this->name; 
      }
    }
     
    $item = new Item(); 
    $item->setName( "widget 5442" ); 
    print $item->getName(); 
    //outputs "widget 5442"
    ?>

    Yep, object operator works for me too!

  9. Yes there is a simple way to understand things such as this. Rudimentiry operators can really become confusing when you are having trouble understanding the whole objects, and classes. Thanks for the smooth, helpful read!

  10. Hi, thank you so much for clarify what these actually do and the differences. My final year dissertation in making a oo php site and I am new to it… absolutely impossible to get a result from google without knowing the names… and there is for some reason pleanty of oo php site but few explaining this. now I can make some progress …. happy face!

  11. Hmm, interesting topic. I would go with: “member selection operator” for “->” as in C++ although I used “derefence operator” a lot.

    Cheers

  12. If I have this array which obviously pulls three values from a much larger array.

    print_r($order->tags);
    shows this content

    Array
    (
    [277] => APM499
    [269] => EPP159
    [273] => WFM060
    )
    How do I pull the value ‘APM499’ out of $order->tags into a variable?

    I have tried a coupe of things, but I haven’t struck gold yet.

    $order->tags[0] is blank
    $order->tags[1] is blank

    How do I find the 277 so that I can use

    $theValueIs = $order->tags[277];

  13. Jim,

    There are a few ways you can approach this, depending upon what you know and what you don’t know. If you know the index of the array, you can access it directly:

    <?php
    $val = $order->tags[277];
    ?>

    If you know the value you are looking (not always the best way since not all values will be unique, but, I digress…) you can always use array_search():

    <?php
    $key = array_search('APM499', $order->tags)
    if ($key) {
      $val = $order->tags[$key];
    }
    ?>

    You can also try looping and comparing, but that seems to be overkill in my opinion. There are many useful array functions that are built in to PHP that you can use though, so I’d recommend spending some time in the manual messing with some of the code examples.

  14. Thanks a lot. Perhaps the root question should be: “Who the heck introduced this confusing notation in the first place?” Sometimes the ABM campaign (anything butt Microsoft) goes too far. This is an instance in which their notation is superior, and it should have been adopted.

  15. Thanks for a very useful discussion – still relevant several years later. I have a follow up question: although “$obj->method();” makes perfect sense, I’m a little surprised that multiple references like this also seem to work (out of code from the very professional DataTables jquery plugin). Note the lag of punctuation after each reference.

    // Build our Editor instance and process the data coming from _POST
    Editor::inst( $db, ‘Supplier_payments’, ‘id’ )
    ->where( “Currency”, “SEK”)
    ->process( $_POST )
    ->json();

  16. Roger,

    The reason that works is because each of those methods returns the object that the method belongs to. It is called method chaining and allows for the combined calling of methods on an object when needed/wanted. At a code level, it looks something like:

    <?php
    class Greeting
    {
        /**
         * The message to parse
         * @var string
         */
        protected $message = 'Greetings %s, how are you %s?';
     
        /**
         * The name for the greeting
         * @var string
         */
        protected $name;
     
        /**
         * The time of day for the greeting
         * @var string
         */
        protected $time;
     
        /**
         * Simple instance getter. Totally not necessary, but useful for the example.
         * @return Greeting
         */
        public static function getInstance()
        {
            return new self;
        }
     
        /**
         * Sets the name property
         * @param string $name The name for the greeting
         * @return Greeting
         */
        public function setName($name)
        {
            $this->name = $name;
            return $this;
        }
     
        /**
         * Sets the time for the greeting
         * @param string $time The time for the greeting
         * @return Greeting
         */
        public function setTime($time)
        {
            $this->time = $time;
            return $this;
        }
     
        /**
         * Returns a parsed string of all the components
         * @return string
         */
        public function parse()
        {
            return sprintf($this->message, $this->name, $this->time);
        }
    }
    ?>

    Which then allows you to do something like this:

    <?php
    // Output: Greetings Robert, how are you this evening?
    echo Greeting::getInstance()->setName('Robert')->setTime('this evening')->parse();
    ?>

    Or, for cleanliness (since PHP doesn’t really care about punctuation, unless you aren’t terminating your line endings correctly):

    <?php
    echo Greeting::getInstance()
         ->setName('Robert')
         ->setTime('this evening')
         ->parse();
    ?>

Leave a Reply

Your email address will not be published. Required fields are marked *