$this and ->

In the PHP manual I keep seeing this arrow symbol -> used in examples of classes and methods. For instance:

[code]<?php
class Cart {
var $items; // Items in our shopping cart

// Add $num articles of $artnr to the cart

function add_item($artnr, $num) {
    $this->items[$artnr] += $num;
}[/code]

and

<?php $cart = new Cart; $cart->add_item("10", 1);

What function does the -> operator serve? Is it like the dot (as in cart.add_item) in Java? And is $this a reserved variable, and if so how does it work?

You’re on the right track :wink:

-> is much like the dot in Java (not exactly the same, but largely). It tells parser there’s a reference to a method (function) or attribute (variable) in a class. For static methods and attributes, :: is used instead of ->.

$this is pretty much the same as Java’s this reference, and can only be used inside class instances (this excludes static methods).

For more information on PHP’s OOP implementation, see here (PHP4) and, which I’d recommend, the PHP5 OOP implementation.

Awesome, so I’ve been reading the Classes and Objects manual for the wrong version of PHP for the past 45 minutes.

Here’s another question: say I left out the $this-> in the first example so that it read thusly:

[code]<?php
class Cart {
var $items; // Items in our shopping cart

// Add $num articles of $artnr to the cart 

function add_item($artnr, $num) { 
    items[$artnr] += $num;  //removed the $this-> from this line
}[/code]

Would this still work? Would it only work from a static context? Or could the class be instantiated while the array would be left static?

For comformity I’d always recommend using $this for class-scope attributes and methods (though I know leaving it out for methods works fine … not sure about attributes though). It works that way in Java :wink:

As for static, I’d say you’d have to check the manual on that. Static is a whole different story and you’d do good not to touch it too much until you get the facts straight on that one (I’ve experienced this first-hand, and thankfully, nothing I did went seriously wrong, but it does give you a clear view on how it’s supposed to be used).

Static members can only be accessed using ::, as per the below example:

[php]
class myClass {
public static foo = “bar”;

public showFoo() {
echo $this->foo; // Probably echoes an empty string, not sure
echo $this::foo; // This is the way to go, will echo ‘bar’
}
}

echo myClass->foo; // Not sure
echo myClass::foo; // Correct way, displays ‘bar’
[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service