Methods in OOP PHP

A method is a function defined inside the class, and it’s defined in this way:

class Dog {
  public function bark() {
    echo 'woof!';
  }
}

Methods are very useful to attach a behavior to an object. In this case we can make a dog bark.

Notice I used the public keyword, that’s to say a method can be invoked from outside the class. Like for properties, you can mark methods as private too, or protected, to restrict its access.

You invoke a method on the object instance like this:

class Dog {
  public function bark() {
    echo 'woof!';
  }
}

$roger = new Dog();

$roger->bark();

A method, just like a function, can define parameters and a return value too.

Inside a method we can access the object’s properties using the special built-in $this variable, which when referenced inside a method points to the current object instance:

class Dog {
  public $name;

  public function bark() {
    echo $this->name . ' barked!';
  }
}

$roger = new Dog();
$roger->name = 'Roger';
$roger->bark();

Notice I used $this->name to set and access the $name property, and not $this->$name.

Download my free PHP Handbook!