5

Possible Duplicate:
Reference - What does this symbol mean in PHP?

Sorry for being so pedantic about this, but I'm confused about the object operator (->). What exactly is it doing and how (to avoid errors and misusing) do I use it?

Community
  • 1
  • 1
Max Z.
  • 801
  • 1
  • 9
  • 25
  • 5
    Please reference [What does this symbol mean in PHP](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Nightfirecat Aug 08 '11 at 22:22

3 Answers3

13

In order to use the object operator, you will need to create and instantiate a class, as follows:

class MyClass {
  public $myVar;

  public function myMethod() {

  }
}

$instance = new MyClass();

$instance->myVar = "Hello World"; // Assign "Hello World" to "myVar"
$instance->myMethod(); // Run "myMethod()"

Let me explain the above code:

  1. First, a class with a name of "MyClass" is created, with a variable of "myVar" and a method (basically a function within a class) with a name of "myMethod".
  2. "$instance" is created, and then it is assigned a new instance of the "MyClass" class.
  3. $instance->myVar, with the object operator accesses the public instance variable within the $instance object, and assigns it a value of "Hello World". Similarly, the "myMethod" is called within the $instance object, also using the object operator.

The object operator is simply PHPs way of accessing, running, or assigning "stuff" within an object.

Hope that helps.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195
5

its just like the . in other languages. eg, if you have a object called ball with method bounce(), in most languages it would be

ball.bounce();

in php it is

ball->bounce();
kennypu
  • 5,950
  • 2
  • 22
  • 28
  • 1
    In other languages, `.` would also do what `::` does in PHP, so this comparison might get confusing. – rid Aug 08 '11 at 22:25
  • @Max, no, `=>` has nothing to do with `->`, it's something completely different. – rid Aug 08 '11 at 22:25
  • 1
    As I said, I was confused... @miku posted a link further down which clarified it :) – Max Z. Aug 08 '11 at 22:26
  • ahh, sorry about the confusion, just thought a simple example would be easier to understand. – kennypu Aug 08 '11 at 22:28
  • Thank you so much, coming from Java this is a great way of explaining it! – nmu Dec 11 '15 at 10:18
2

The object operator, "->", is used in object scope to access methods and properties of an object. It's meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator.

From: http://www.robert-gonzalez.com/2009/03/04/php-operators-double-and-single-arrow/

Other languages use the dot notation for this, like obj.meth().

miku
  • 181,842
  • 47
  • 306
  • 310