Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object operator in PHP (->) [duplicate]

Tags:

php

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?

like image 366
Max Z. Avatar asked Aug 08 '11 22:08

Max Z.


2 Answers

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.

like image 82
Oliver Spryn Avatar answered Oct 04 '22 04:10

Oliver Spryn


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();
like image 41
kennypu Avatar answered Oct 04 '22 05:10

kennypu