Jump to content


Photo

What does -> & => do?


  • Please log in to reply
No replies to this topic

#1 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 14 June 2006 - 03:21 PM

Q: What do the following operators do: -> and => ?>
A:

The -> Operator

The -> opertator is used in Object Oriented Programming (OOP for short) to call methods/variables from within an object for example you have this class:
<?php
class foobar {
    function foo() {
        echo "Foo initiated";
    }

    function bar() {
        echo "Bar initiated";
    }
}
To call the foo function you first need to create the object by doing this:
$obj = new foobar;
Now you need use the -> operator to call the method within the object:
$obj->foo();

// the same for calling bar() too:
$obj->bar();

The => Operator

But the  => operator is used when dealing with arrays. It is used to define the key for an item within an array. For example
$person = array("name" => "John", "age" => 24);
So with that code you are you are creating two keys, the first one is 'name' which stores 'John' and a secound key called 'age' which stores the number '24'

Now that you have defined the key for each item in the array you can use this code:
echo $person['name']; //yields "John"
echo $person['age']; //yeilds 24

If you didn't define a key in your array you'll have to get the value from the array like so
echo $person[0]; //yields "John"
echo $person[1]; //yields 24

=> can also be used in foreach loops, but it used to get the value of the key rather than assing the key, you may use this when debugging POST'd data for example:
foreach($_POST as $k => $v) {
    echo "'" . $k . "' = " . $v;
}





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users