Object Methods

A method is a function defined within a class. Every object instantiated from the class has the method’s functionality. Listing 9.1 adds a method to the Item class (line 5).

Listing 9.1. A Class with a Method
 1: <?php
 2:class Item {
 3:  var $name = "item";
 4:
 5:  function getName() {
 6:    return "item";
 7:  }
 8: }
 9:
10: $item = new Item ();
11: print $item->getName ();
12: // outputs "item"
13: ?>

As you can see, a method looks and behaves much like a normal function. A method is always defined within a class, however. You can call an object method using the -> operator. Importantly, methods have access to the class’s member variables. In Listing 9.2, we return the string "item" when asked for the Item object’s name. Clearly, ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.