Object operator in PHP (->) [duplicate]
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 (->). W开发者_开发百科hat exactly is it doing and how (to avoid errors and misusing) do I use it?
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:
- 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".
- "$instance" is created, and then it is assigned a new instance of the "MyClass" class.
- $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.
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();
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()
.
精彩评论