Reputation: 2815
I see these in PHP all the time, but I don't have a clue as to what they actually mean. What does ->
do and what does =>
do?
And I'm not talking about the operators. They're something else, but nobody seems to know...
Upvotes: 279
Views: 530161
Reputation: 4591
The double arrow operator, =>
, is used as an access mechanism for arrays (and also in many other cases explained in the answer below). 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.
$myArray = array(
0 => 'Big',
1 => 'Small',
2 => 'Up',
3 => 'Down'
);
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.
// Create a new instance of MyObject into $obj
$obj = new MyObject();
// Set a property in the $obj object called thisProperty
$obj->thisProperty = 'Fred';
// Call a method of the $obj object named getProperty
$obj->getProperty();
Upvotes: 418
Reputation: 29
1. -> Object Operator
(->) accesses an object's properties and methods, allowing for method calls or property retrieval from an object instance.
class Car {
public $color = 'red';
public function drive() {
echo "The car is driving.";
}
}
$myCar = new Car();
// Accessing the property
echo $myCar->color; // Output: red
// Calling the method
$myCar->drive(); // Output: The car is driving.
$myCar->color accesses the color property, while $myCar->drive() invokes the drive method of the $myCar object.
2. => Array Key-Value Separator
(=>) associates keys with values in an associative array, creating key-value pairs.
$person = [
'name' => 'Alice',
'age' => 30,
'job' => 'Engineer'
];
echo $person['name']; // Output: Alice
In this example, 'name' => 'Alice' establishes a key-value pair with 'name' as the key and 'Alice' as the value. You can access the value using the key like this: $person['name'].
Upvotes: 0
Reputation: 1634
->
is used to call a method, or access a property, on the object of a class
=>
is used
to define array members, e.g.:
$ages = ["Peter" => 32, "Quagmire" => 30, "Joe" => 34, 1 => 2];
to make foreach return the key along with value
foreach ($ages as $name => $age) {
echo "$name is $age years old";
}
since PHP 7.4 =>
operator is also used for the arrow functions, a more concise syntax for anonymous functions.
since PHP 8.0 =>
operator is also used to define hands in the match expression
Upvotes: 84
Reputation: 16828
calls/sets object variables. Example:
$obj = new StdClass;
$obj->foo = 'bar';
var_dump($obj);
Sets key/value pairs for arrays. Example:
$array = array(
'foo' => 'bar'
);
var_dump($array);
Upvotes: 32