PHP - Creating Class Methods

Introduction

A class method is much like a function, except that it's tied to a specific class.

Method Visibility

A property can have three visibility levels: public, private, and protected. The same is true of methods.

All methods can be called by other methods within the same class.

  • If a method is declared public, any code outside the class definition can also potentially call the method.
  • If a method is declared private, only other methods within the same class can call it.
  • A protected method can be called by other methods in the class, or in a class that inherits from the class.

To add a method to a class, use the public, private, or protected keyword, then the function keyword, followed by the method name, followed by parentheses.

You then include the method's code within curly braces:

class MyClass {

           public function aMethod() {
             // (do stuff here)
           }

}

You can optionally leave out the public, private, or protected keyword.

If you do this, public is assumed.

Related Topic