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 = "[email protected]";

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.

2
  • It's not a duplicate of either of those two things, but thanks anyway. Commented Apr 4, 2011 at 20:26
  • See here that second possible duplicate was incorrect. Commented Apr 4, 2011 at 20:39

3 Answers 3

4

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

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

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.

1
  • 2
    Apparently its official name is "object operator". Commented Apr 4, 2011 at 20:36
2

$e is an object.

That object has the function errorMessage()

Therefore you are calling $e's function

Not the answer you're looking for? Browse other questions tagged or ask your own question.