Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a difference between a method and a function?

Tags:

php

What is the difference between a method and a function? Is it that a method returns a value and a function doesn't?

like image 679
Amol Avatar asked Jan 30 '11 06:01

Amol


2 Answers

Method is actually a function used in the context of a class/object.

When you create a function outside of a class/object, you can call it a function but when you create a function inside a class, you can call it a method.

class foo {    public function bar() { // a method      ........    } } 

function bar() {  // a function not part of an object } 

So an object can have methods (functions) and properties (variables).

like image 72
Sarfraz Avatar answered Oct 05 '22 04:10

Sarfraz


The words are not opposed to each other but rather describes two possible aspects of a subroutine. An attempt to define the words follows:

Subroutine: A set of instructions that can be used several times in the same program.

Function: A subroutine that returns a value. Derived from functions in mathematics (wikipedia).

Method: A subroutine that belongs to an object or a class. Could be a function.

I tend to use the word "function" for every subroutine that has no side effects but returns one clear value and the word "method" for every subroutine that has a side effect.

like image 33
Jonatan Avatar answered Oct 05 '22 05:10

Jonatan