When to Use a Class VS. Function in PHP

When to use a Class vs. Function in PHP

Classes are used for representing data as objects. If you're representing something like a user's data, or an auction bid, creating a User object or AuctionBid object makes it easier to keep that data together, pass it around in your code, and make it more easily understandable to readers. These classes would have attributes (data fields like numbers, strings, or other objects) as well as methods (functions that you can operate on any class).

Classes don't usually offer any benefits in terms of performance, but they very rarely have any negative effects either. Their real benefit is in making the code clearer.

I recommend you read the PHP5 Object-Oriented Programming guide and the Wikipedia OOP entry.

What is the difference between class and function in php?

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 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.

Classes vs. Functions

Create a function. Functions do specific things, classes are specific things.

Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.

Essentially, a class is a way of grouping functions (as methods) and data (as properties) into a logical unit revolving around a certain kind of thing. If you don't need that grouping, there's no need to make a class.

Why should I use classes rather than just a collection of functions?

It's a way to view your code in a more intuitive, real-world way. (You package the data and all possible operations on that data together.) It also encourages encapsulation, abstraction, data hiding... What you're really looking for is the advantages of OOP.

PHP OOP Class vs Functions vs Static Functions efficiency

we may create other classes indeed, but efficiently so. Maybe we can render DB a public state function. I like the idea of creating a database object, pass it as parameter to an other object, which could then format data with the link he just received:

$pg_ID = 2;
$db = new DB($pg_id);
$page = new Page($db,$pg_ID);
// make sure you assign the parameters a private properties in `Page()` ctor.

then, from inside your function, you can call images, titles and structures at will from $this

$title = $this->DB->get('pages', $this->pgID, $lang);
$images = $this->DB->get('images', $this->pgID, $lang);
$structure = $this->DB->get('pages_list', $this->pgID);

and you can those other method as well

$page->find('pages', $this->pgID, $lang);
$page->lookup($this->pgID);
$page->retrieve('images', $this->pgID, $lang);

Now we do not need to create a new object each time we want information from the database.

Now...

the way I access member functions here $this->pgID is better used by defining a getter: $this->pgID(). I like my getter to have the same name as the property. This might not be a very good idea though.

private function pgID() {
return $this->pgID;
}

As for abstract classes..

I did in fact come very lately into thinking abstract classes were quite cool indeed. I've some problem with wording it, having a constant constructor with custom mandatory functions and possible different implementation of classes seems awesome:

abstract class Page {
function __construct($db,$pgID,$lang,$params='') {
$this->db = $db;
$this->pgID = $pgID;
$this->lang = $lang;
$this->init($params);
}
function pgID() {
return $this->pgID;
}
function lang() {
return $this->lang;
}
abstract function init();
abstract function retrieve();
}

class Structure extends Page {
function init($params) {
// some specific to Structure foo here
}
function retrieve($what='pages_list') {
return $this->db->get($what,$this->pgID,$this->lang);
}
}

class Image extends Page {
function init($params) {
// some specific to Image foo here
}
function retrieve($what='images') {
$images = $this->db->get($what,$this->pgID,$this->lang);
// plus some foo to resize each images
return $images;
}
}

ok, hope you're still there! Now we have a Structure and Image class with requisites constructor arguments, generic functions and a custom retrieve function. We could use them that way:

$db = new DB(2);
$template = new Structure($db,2,'fr');
$template->retrieve();

$slideshow = new Image($db,4,'en');
$slideshow->retrieve();

I do hope you do not have to create a new instance of DB if you use a different page id :-)

jokes appart this helps me using classes in a better structured way, as I might have many different classes to represent different parts of a site, but when called from an index all of them will have the same function names, like retrieve() or print(), list()...

PHP Classes: when to use :: vs. -?

Simply put, :: is for class-level properties, and -> is for object-level properties.

If the property belongs to the class, use ::

If the property belongs to an instance of the class, use ->

class Tester
{
public $foo;
const BLAH;

public static function bar(){}
}

$t = new Tester;
$t->foo;
Tester::bar();
Tester::BLAH;

Difference between functions and public functions in classes

Omitting the visibility is legacy code. PHP 4 did not support public, protected and private, all methods were public.

Short: "public function" == "function" // true

See also the PHP manual:

// This is public
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}

Similarly var $attribute; is equivalent to public $attribute. The var version also is PHP 4 legacy code.

What's the difference between using normal functions and class methods in PHP?

OOP provides, among other things, encapsulation.

class Shop {

function __construct($items) {
$this->inventory = $items;
}

function deleteItem($item) {
$key = array_search($item, $this->inventory);
if ($key !== false)
unset($this->inventory[$key]);
}

}

Now you can create instances:

$computerShop  = new Shop(array('ram', 'monitor', 'cpu', 'water'));
$hardwareStore = new Shop(array('hammer', 'screwdriver', 'water'));

And each one of them is independent from each other. If I do $computerShop->removeItem('water'), $hardwareStore should still have water in their inventory. (see it in action) Doing this the procedural way is much messier.


Another cool thing about OOP is that you can use inheritance and polymorphism:

class Animal {

function eat() {
$this->hungry = false;
}

abstract function speak();
}

class Cat extends Animal {

function speak() {
echo 'meow!';
}
}

class Dog extends Animal {

function speak() {
echo 'woof!';
}
}

Now both Cat and Dogs can call the method eat() even though they are not explicitly declared in their classes - it's been inherited from their parent class Animal. They also have a speak() method that does different things. Pretty neat, huh?

Wikipedia:

Object-oriented programming, Encapsulation, Inheritance, Polymorphism

What is a difference between a method and a function?

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).



Related Topics



Leave a reply



Submit