How to use -> and => in PHP

February 24th, 2006 by Sarah King

I just saw a forum post asking the difference between -> and => and it's one of those tricky questions to research, just how can a search engine understand what you're asking?

Well, luckily the answer is quite simple.

-> is used by objects to set, get or call a method of that object.
Ref: Chapter 18. Classes and Objects (PHP 4)

=> is used by arrays to describe the relationship between the key and the value
Ref: Arrays

Here's an example of how the -> is used in a class

PHP:
  1. class fruit{
  2.     var $color;
  3.     var $price;
  4.     var $quantity;
  5.    
  6.     function getTotal()
  7.     {
  8.         $total = $this->price * $this->quantity;
  9.         return $total;
  10.     }
  11. }
  12.  
  13. $apple = new Fruit();
  14. $apple->color = 'red';
  15. $apple->price = 1;
  16. echo $apple->getTotal();

and here is how => is used in an array. Despite constructing $apple and $pear in different ways, the arrays are structurally the same and should output the same information when the script is run.

PHP:
  1. $apple = array();
  2. $apple['price'] = 1;
  3. $apple['color'] = 'red';
  4.  
  5. $pear = array('price' => 2, 'color' => 'green');
  6.  
  7. foreach($apple as $key => $val) {
  8.     echo "{$key}: {$val}<br />";
  9. }
  10. foreach($pear as $key => $val) {
  11.     echo "{$key}: {$val}<br />";
  12. }

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Twitter
  • StumbleUpon
  • Mixx
  • Google Bookmarks
  • Blogplay
  • Add to favorites
  • Sphinn
  • NewsVine
  • Propeller
  • Yahoo! Bookmarks
  • Yahoo! Buzz

Leave a Reply

You must be logged in to post a comment.