I have downloaded a WordPress theme and in many places in the code I see the operator ->. It could be for example to retrieve a post ID like this:
$postID = $post->ID
I can’t find what the arrow actually does in the background. Does it make a database call? Or is it simply fetching the ID from the $post variable, similar to $postID = $post['ID']
?
2
Answers
The arrow operator
->
is for accessing properties or method of an object.Overhead of accessing properties is neglectible, but it’s sometimes more comfortable to assign a property to a temporary variable, just because it shortens the source code. Example
However, it’s often a good practice to save the return value of an method call to a temporary variable to avoid to much overhead. For example if the method performs a database query (and has no build-in caching), it would cause massive overhead to call the method over and over instead of calling it once an then reuse the value, f.e. in a loop.
But it also depends on how a method is used and what it’s doing. If it takes arguments, you might need to call it repeatedly with changing parameters, in order to get the job done.
in PHP -> simply means it is accessing object properties, like how ‘.’ works in other Object Oriented Languages like java.