8

Possible Duplicates:
Reference - What does this symbol mean in PHP?
In, PHP, what is the “->” operator called and how do you say it when reading code out loud?

This is a really newbie question, so apologies in advance, but I've seen -> used several times in example code, but I can't seem to find any explanation in online tutorials for what it does. (Mainly because Google ignores it as a search term - doh!)

Here's an example that confuses me:

<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "someone@example.com";

try
  {
  //check if
  if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
    {
    //throw exception if email is not valid
    throw new customException($email);
    }
  //check for "example" in mail address
  if(strpos($email, "example") !== FALSE)
    {
    throw new Exception("$email is an example e-mail");
    }
  }

catch (customException $e)
  {
  echo $e->errorMessage();
  }

catch(Exception $e)
  {
  echo $e->getMessage();
  }
?> 

What is going on in lines such as echo $e->errorMessage();? It looks like its passing the variable $e to the function errorMessage(), but if so, why not just do it in the more traditional way?

Thanks for any help.

Community
  • 1
  • 1
Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289

3 Answers3

4

It's used in object oriented programming to denote object->property

echo "$foo->bar" would echo the bar property of $foo

Levi Hackwith
  • 9,232
  • 18
  • 64
  • 115
2

$e is an object.

That object has the function errorMessage()

Therefore you are calling $e's function

Naftali
  • 144,921
  • 39
  • 244
  • 303
2

No, it is not a scope resolution operator. :: (also called Paamayim Nekudotayim) is the scope resolution operator, see the manual.

No, it is not a function. This is object oriented programming, so the correct term is method.

No, it is not a property. Again, it's a method.

I am not aware of any terminology for the -> construct. It is used to either call methods or to access properties on an instance of a class. On an object. I suppose you could refer to it as the "instance operator".

In your specific case it's a method call. The errorMessage method is being called on your $e object, which is an instance of the customException class.

igorw
  • 27,759
  • 5
  • 78
  • 90