2

is there any performance difference ? whats the main difference anyway ? and there is more like

public static function
static public function

is it the same ?

sorry for a newbie question thanks for looking in

Adam Ramadhan

Adam Ramadhan
  • 22,712
  • 28
  • 84
  • 124

2 Answers2

2

There is no difference in the two :

public static function
static public function

Both a accessible outside of the class. In both, you can't use $this inside the function because a static function does not requiere an object to be instanciated.

Consider you have a Cars class.

// Constructors call to a private static function add_this_car();
$car1 = new Cars('bentley');
$car2 = new Cars('Porsche GT1');

// public static function get_created_cars();
$all_cars = Cars::get_created_cars();

This way a class can take care of all instances of it there is (and a reference to each). And things that should be handle by the class itself and do not requiere an instance to be created.

Sébastien VINCENT
  • 1,096
  • 6
  • 11
  • jessy said ( irc #php ) static means it's defined at the class scope rathar than object scope, i just don't understand static things ( i never used them ) , i mean how they work, etc in object oriented programming especialy in php. i use like $this-> not this:: or with the :: static magic thing. :) , i hope you get what i mean – Adam Ramadhan Nov 13 '10 at 07:32
  • Does this edit answer to your question on how to use the "static" functions ? – Sébastien VINCENT Nov 13 '10 at 07:37
  • so the olny difference is that we dont have to init them ? is there another difference like performance or anything ? – Adam Ramadhan Nov 13 '10 at 07:45
  • 1
    I found a Bench here on Stack Overflow, take a look it's very interesting : http://stackoverflow.com/questions/1472721/php-performance-of-static-methods-vs-functions – Sébastien VINCENT Nov 13 '10 at 07:51
1

Think of a class full of static methods like a nifty container to hold related functions together.

Say you want to create a class full of your favorite string formatting functions.

Then you can say MyClass::MakeUppercase($string) to make the string upper case. You can say MyClass::MakeLowercase($string) to make the string lower case.

Since your utility class doesn't represent any kind of object, and doesn't have any kind of internal state to keep track of, you have no reason to instantiate objects of it. No $myvar = new MyClass() before you can use the functions. That'd just waste memory creating objects that never have different internal states to keep track of.

Dan Grossman
  • 51,866
  • 10
  • 112
  • 101