EDDYMENS

Published a year ago

What Is A Method In Programming?

Table of contents

Definition

A method is a function [→] that is part of a class [→].

Example

01: <?php 02: 03: class Car { 04: 05: public $make = []; 06: 07: public function __construct($brand, $model, $year, $start=true) { 08: $this->make = [ 09: 'brand' => $brand, 10: 'model' => $model, 11: 'year' => $year 12: ]; 13: return $this->startOrStop($start); 14: } 15: 16: public function accelerate() { 17: // acceleration method 18: return $this; 19: } 20: 21: public function break() { 22: // breaking method 23: return $this; 24: } 25: 26: public function moveLeft() { 27: // direction method 28: return $this; 29: } 30: 31: public function moveRight() { 32: // direction method 33: return $this; 34: } 35: 36: public function startOrStop($state) { 37: // ignition method 38: return $this; 39: } 40: 41: }

The functions accelerate, break, moveLeft, moveRight, startOrStop in the code above are all methods of the Car class.

Summary

A method unlike a generic function has direct access to other properties/data within its defined class whereas with generic functions you have to explicitly pass the data to it.

Here is another article you might like 😊 What Is A Class In Programming?