what does -> mean?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jiehuang001
Forum Commoner
Posts: 39
Joined: Mon May 12, 2003 12:53 pm

what does -> mean?

Post by jiehuang001 »

Can someone tell me what "->" does in PHP. I think in C++ there is also such a symbol.

Below is a piece of code from PHP Manual that used "->"

function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}

Thanks.

Jie Huang
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

-> is used in classes.

Code: Select all

<?php
$this->readMe="How nice of you";
?>
assigns the string "How nice of you" to the class-variable (or class-property if you like) in the class itself.
"$this" stands for the current instance of the class.

If you would be doing the same thing from outside the class it would look something like this

Code: Select all

<?php
$readup=new myReadingClass;
$readup->readMe="How nice of you";
?>
I am sure you'll find some good object-oriented programming guides if you look with google.
jiehuang001
Forum Commoner
Posts: 39
Joined: Mon May 12, 2003 12:53 pm

Post by jiehuang001 »

so you mean "->" is similar as the "." in other language such as Java?
and below is the usage?

$instance_of_class -> variable_in_instance = the_value_to_be_assigned
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

I don't know Java, but the code-sample you provide is correct.
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

Yes PHP's '->' is the same as Java's '.'. Its the member attribute/method selector used on a class instance. PHP also uses the '::' operate to call static functions off a non-instantiated class.

Mini history of -> from C:

The '->' operator comes from C where var->something was converted to (*var).something. Where var is most typically a "struct" aka a 'record' in Pascal, or a "method-less class with all public variables" in Java. Due to C being a pass-by-value languange, pointers were needed to let functions change their arguments. Structs were the major type used for making data structures so you can imagine they are always being passed around and needing to be changed. Typeing (* ). (five characters) all the time got old so someone (classic lazy hacker syndrome) created -> (two characters) as "syntatic sugar". (The parenthesis were needed because '.' had a higher order of precendence than the variable deference.
Post Reply