0

Hello
I m not clear about class. Can anybody help me. Actually what is different between class and function. When I will use functiona and when I will use function.

7
Contributors
10
Replies
16
Views
6 Years
Discussion Span
Last Post by fpaquin
Featured Replies
  • The PHP Language reference has details on what a function and class is: [url]http://www.php.net/manual/en/langref.php[/url] It also explains most the other features of PHP. If want to learn PHP that is the best place to start. [B]Functions[/B] The function is a grouping of statements (lines of code). For example the following … Read More

4

The PHP Language reference has details on what a function and class is:
http://www.php.net/manual/en/langref.php

It also explains most the other features of PHP. If want to learn PHP that is the best place to start.

Functions

The function is a grouping of statements (lines of code).

For example the following statements:

$name = 'mary';
$gender = 'girl';

if ($gender == 'girl') {
  $line = $name . ' had a little pony.';
} else if ($gender == 'boy') {
  $line = $name . ' had a little horse.';
}
echo $line;

Can be grouped together into a function so it can be reused:

getSentence('mary', 'girl');
getSentence('peter', 'boy');

function getSentence($name, $gender) {
  if ($gender == 'girl') {
    $line = $name . ' had a little pony.';
  } else if ($gender == 'boy') {
    $line = $name . ' had a little horse.';
  }
  echo $line;
}

Notice the two function calls:

getSentence('mary', 'girl');
getSentence('peter', 'boy');

These two statements run the whole block of code inside the getSentence function and pass it the variables $name and $gender.
With the first function $name = 'mary' and $gender = 'girl' and in the second $name = 'peter' and $gender = 'boy'.

So the main benefit of functions is that you have grouped code for reuse, allowing the passing of different values for the variables needed by the function. These variables are called the function parameters.

Another benefit of having the code grouped is easier readability. You are essentially naming the block of code, and giving them a specific purpose. Making it easy to read and remember it's use.

Another benefit is that redundancy is removed. You do not have to write the block of code more then once. You just define it once, and call it multiple times. This also makes editing of the function code affect all calls to that function - which reduces errors in having to edit multiple locations when changing just one aspect.

eg:

We can make sure the $name string has an uppercase first character.

function getSentence($name, $gender) {
  $name = ucfirst($name);
  if ($gender == 'girl') {
    $line = $name . ' had a little pony.';
  } else if ($gender == 'boy') {
    $line = $name . ' had a little horse.';
  }
  echo $line;
}

We made just one change, and it affected every function call to getSentence(). In this case both: getSentence('mary', 'girl'); and getSentence('peter', 'boy'); Classes

Classes are a grouping of functions.

class Play {

  function getSentence($name, $gender) {
    $name = ucfirst($name);
    if ($gender == 'girl') {
      $line = $name . ' had a little pony.';
    } else if ($gender == 'boy') {
      $line = $name . ' had a little horse.';
    }
    echo $line;
  }

  function getSong($name) {
    // code here
  }

}

All we did was put

class Play { /** functions here **/ }

around a group of functions.

This offers the same benefits that functions do for statements except classes does it for functions.

Classes go further to build a programming methodology called Object Oriented programming (OOP), which you can read more about in link to PHP Language reference.

This defines classes as the template or definition of Objects. Objects being similar to real world objects, with the functions being called "methods" that can be called for the object.

So the class Play can be thought of as the object called "Play" with the methods "getSentence" and "getSong". These methods can then manipulate the properties of the object "Play" or return useful information about "Play". In this way, all the code inside Play becomes independent of code elsewhere in the program.

When the code inside Play requires some code elsewhere to function, it can be brought in using "inheritance", which is a major part of OOP. I will not go into detail about this as it is a very broad topic.

I would recommend getting a book on OOP and reading it to really understand why you should use classes and methods and when to use them.

Edited by digital-ether: n/a

Votes + Comments
You couldn't ask for a fuller explaination. Love it!
0

Of course digital-ether answer is more accurate but to make thinks a bit simpler associate class with the object and function with the behavior of the object. To go many years back, if the object-class is a bicycle it has attributes (color, speed) and behavior (changeColor , changeSpeed), the function is the behavior. Of course PHP can have behaviors outside objects. In this case think them as an encapsulation of code for readability and reusability.

0

Still it is not clear to me. Can u explain that what can be done by class but not by function?

0

A function can communicate with other function passing variables and receiving from them. Just imagine if function not only passing variables to each others but being a part of a larger universe. Then they could exchange data and behavior inside their universe. You could use one function from a class (a universe) and automatically all the other functions from this one know exactly what you do. Then this universe could have some attributes that it’s functions could change. Class is a universe … you are programming in a multiple universes … To be just, class comes form the word taksi from Aristotle who from that word defines specie by its attributes and behaviors. That is exactly a class in OOP and in PHP , while function encapsulate a behavior without a context class is the context.

0

Correction: after few research it isn’t the word taksis that Aristotle used but klasis that in Latin became class.

0

@arctushar
I had the same problem understanding function and class, and how do they differ ...
Ok now I have 90% understood what does the class exactly offer us!

Function example:

function CommentHtmlentites($comment)
{
   1)make the comment htmlentities
   2)echo the comment
}

fcuntion CommentNl2br($comment)
{
   1)make the comment nl2br
   2)echo the comment
}

Class example:

class Comment
{
   function MakeCommentHtmlentites($commentHere)
   {
      1) Make the comment htmlentites
   }

   function MakeCommentNl2br($commentHere)
   {
      2) Make the comment nl2br
   }

   function EchoComment()
   {
      3) echo the comment
   }
}

Ok now after doing these two example, let's display the comment:

First Using Function

CommentHtmlentites('This is a Comment With Htmlenties');
CommentNl2br('This is a Comment With Nl2br');

Second Using Class

$Comment = new Comment();
$Comment -> MakeCommentHtmlentites('This make the comment Htmlenties');
$Comment -> MlaeCommentNl2br('This make the comment Nl2br');
$Comment -> EchoComment(); // This will echo the comment After Htmlenties and Nl2br

So In Conclusion, Class gives the chance to choose between Htmlentities or Nl2br or both,
But in functions you only can echo comment with Htmlenties or Nl2br
To echo comment in function example with Htmlenties and Nl2br, you must have to create another function with both Nl2br and Htmlenties

Hope this Helps !! And remember this is a small example!! When you will create a big software, you will feel the difference
BR

Votes + Comments
I like this comment. this more helpful
0

I don't know if the previous example is that useful:

function Comment($comment,$html=false,$nl2br=false){
  if($html)$comment = htmlentities($comment);
  if($nl2br)$comment = nl2br($comment);     
  return $comment;
}

//usage:

echo Comment($comment,false,true);

//will nl2br the comment
class Comment{
  private $txt;

  public function __construct($comment){
    $this->txt = $comment;
  }

  public function Clean($html=false,$nl2br=false){
    if($html)$this->txt = htmlentities($this->txt);
    if($nl2br)$this->txt = nl2br($this->txt);     
    return $this->txt;
  }
...
}
//usage:
$t = new Comment($comment);
echo t->Clean(false,true);
//will nl2br the comment

Edited by diafol: n/a

0

Still I m confused. I think the class functions can be done by using function.

0

Of course you can use plain functions. For reusability's sake classes and methods are usually preferred.

0

Class has internal functions and also internal variables. These variables can stay alive as long as the class is not destroyed. As an example, you can have a class that contains 2 variables and 4 founctions that act on the variables. You don't need to reset the variables if you use the functions in the class. The syntax may not be correct because I come from the Java world.

class Calc {

    private $var1;
    private $var2;

    public function store($v1, $v2) {
        $var1 = $v1;
        $var2 = $v2;
    }

    public function add() {
        echo $var1 + $var2;
    }

    public function substract() {
        echo $var1 - $var2;
    }

    public function multiply() {
        echo $var1 * $var2;
    }

    public function divide() {
        echo $var1 / $var2;
    }
}


$calculate = new Calc();

$calculate->store(4,5);
$calculate->add(); //result 9
$calculate->substract(); //result -1
$calculate->multiply(); //result 20
$calculate->divide(); //result 0.8
$calculate->store(6,7);
$calculate->add(); //result 13

Classes can also act as arrays:

class Row {
    private $col1;
    private $col2;
    private $col3;
    private $col4;

    public function store($v1,$v2,$v3,$v4) {
        $col1 = $v1;
        $col2 = $v2;
        $col3 = $v3;
        $col4 = $v4;
    }
}

I am not sure but I believe PHP classes have constructors. You may use the constructor instead of the store function:

class Row {
   function __construct($v1,$v2,$v3,$v4) {
        $col1 = $v1;
        $col2 = $v2;
        $col3 = $v3;
        $col4 = $v4;
    }

$myRow = new Row(3,5,4,8);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.