Home > Software engineering >  What is the -> (forward arrow) operator in Wordpress/PHP?
What is the -> (forward arrow) operator in Wordpress/PHP?

Time:01-15

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']?

CodePudding user response:

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

$oPropValue = $objWithSpeakingName->propertyWithLongName;

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.

$propValue = $objWithSpeakingName->doSomeWork();
while( ..condition.. ) {
    // work with $propValue
}

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.

while(..condition..) {
    $arg = .. // might change in the loop
    $propValue = $objWithSpeakingName->doMoreWork( $arg );
}

CodePudding user response:

in PHP -> simply means it is accessing object properties, like how '.' works in other Object Oriented Languages like java.

  • Related