Hacker Dewdie Hacker Dewdie - 6 months ago 21
PHP Question

What is the difference between static functions and function outside of a class in PHP?

I need to have method to get something from a database, but I don't understand the difference between static and normal functions in PHP.

Example code

class Item {
public static function getDetail($arg) {
$detail = $this->findProductId($arg);
return $detail;
}

private function findProductId($id) {
//find product_id in database where id = $arg
//return detail of product
}
}


and function outside of a class

function getDetail($arg) {
$detail = findProductId($arg);
return $detail;
}


If I use
$item = Item::getDetail(15);
and
$item = getDetail(15);
— they're the same.


  1. What is the difference between static and function outside of a class?

  2. If they are difference, How to use static function and function outside of a class? (I'd appreciate a really simple example.)

  3. What are the performance properties between static and function outside of a class? Which is better?


Answer

1) What is difference between static function and normal function

While they are functions, I'd prefer to call them methods of a given class. One is a static method and the other is an instance method.

Static Method: $item = Item::getDetail(15);

Instance Method: $item = getDetail(15);

(refer to FuzzyTree's correct syntax above in the comments, however.)

2) How to use static function and normal function (if you simple exemplify is good)

Static means you do not have to instantiate (declare an object reference). That is, you can simply use the method. So, in your example, while the answer may be the same, the way you called that method/function is different, as you noted above.

In Java, for example, you have the Math class. It does not require instantiation to use, and in fact you cannot that I know of because its constructor is private. You can simply use a method by referencing the class and the method name you wish to use,

Math.pow(d1, d2);  //no instantiation needed

in PHP this might be,

MyClass::pow(d1,d2); //no instantiation needed

Java: when to use static methods

3) Ask performance between static function and normal function. Which is better?

Better is a matter of your design. If you have to create an object every time you want to do the power of a number that will create more memoryusage than simply using the class directly. I do not have benchmark proof, but it seem logical since you are not handling the method the same way in memory. I do not think it will matter in real world unless you are doing a lot of complicated actions.

Performance of static methods vs instance methods

might also interest you.

Comments