Object Oriented

Method

PHP

 

Defining Method

PHP 5
class Person {
  
  public function greet() {
    print('Hi!');
  }
  
}

Methods are actions performed on objects.

Methods are like functions, They may get some input and may return a value.

If a method finishes without returning anything, the return value will be NULL.

The public keyword defines the visibility of the Method. (Check Visibility Topic for more on this)

 

Method Parameters

PHP 5
class Person {

  public $name;

  public function getName() {
    return $this->name;
  }

  public function setName($name) {
    $this->name = $name;
  }

  public function sleep($from, $duration) {
    $output = $this->getName() . ' slept from ' .
      $from . ' for ' . $duration . ' hours.';
    print($output);
  }

}

Parameters are inputs to methods.

Parameters are separated by comma (,).

Parameters after PHP 7 can have Type hints.

Parameters of type array or object are passed by reference.

Parameters of other types are passed by value.

 

Type Hints

PHP 7
class Person {
  
  // ...

  public function getName() : string {
    return $this->name;
  }

  public function setName(string $name) : void {
    $this->name = $name;
  }

  public function sleep(int $from, int $duration) {
    $output = $this->getName() . ' slept from ' .
      $from . ' for ' . $duration . ' hours.';
    print($output);
  }
  
}

From PHP 7, Method parameters and return values can be type hinted.

PHP engine tries its best to cast values whenever different types are passed.

 

Invoking Methods

PHP 5
$person1 = new Person();

$person1->setName('Sam');
$name = $person1->getName(); // Sam
$person1->sleep(10, 7); // Sam slept from 10 for 7 hours.

Methods of an object can be accessed like any properties on it.

 

Invoking Methods from inside Class

PHP 5
class Person {
  
  // ...
  
  public function birthday() {
    $this->setAge($this->getAge() + 1);
  }
  
}

Methods can be accessed from inside a class explicitly by calling it on $this.