Very recently, I read an article about PHP arrow operators. The article was well written and I felt that I should share my knowledge as well on the topic. Well, PHP is an OOP language as you all might know. Encapsulation, polymorphism, abstraction and inheritance – the four pillars of OOP tell us that class-object relationship plays a very vital role. PHP frameworks and applications follow strict patterns of the latter mentioned concept. So, one must be very sheer about PHP basics.
PHP arrow operators concepts
One of the most basic examples where we can see the implementation of PHP arrow operators is the class object relationship. Suppose you declare a class, you would have some member variables to go with it. Most classes also define member functions or methods specific to itself. In this way, data encapsulation is preserved. Now, when a code block accesses class data, it does with the help of the -> operator. For a better understanding of PHP arrow operators, let us just walk through some code. So, considering the following code, we can say that “$a” is a variable that stores value returned from the function sum (). Since method “sum” is a member method of class calculation, it must be referenced by an object of that class. So, when we create an object, say c, we call the method using -> operator.
// Creating object for class calculation $c = new calculation(); // Calling member method sum and storing in variable a $a = $c->sum();
PHP arrow operators code snippets
This was a good example of PHP arrow operators usage. Another very important section is arrays. Arrays are a vital and pivotal concept in programming. PHP implements the use of associative arrays. These arrays have the facilities of arranging a key value pair. So, at the index there is the key and the value assigned is called the value. PHP arrow operators do have vital differences. => is used to link key value pairs in an array. Consider the following code. For a normal array declaration, the actual PHP key value pairing can be deduced as below.
$a = array('abc', 'def', 'ghi'); // which actually means... $a = array(  => 'abc',  => 'def',  => 'ghi', );
However, this is where PHP arrow operators play an important role. If we want the index positions to be string in place of numbers, we need the => operator. For a key value pair assignment of an associative array => plays the assigning operator. Just look into the following code and you would get to know.
// Use of => operator for string indexes or keys $a = array( 'first' => 'abc', 'second' => 'def', 'third' => 'ghi' );
Often new programmers get confused with the PHP arrow operators and their usage. I hope this tutorial does its part in helping them out.