tags:

views:

83

answers:

3

I am trying to learn OO and classes and all that good stuff in PHP, I am finally learning the sytax good enough to use it some and I am curious if there is any benefit of starting a new object instead of just using static methods...let me show some code for what I mean...

<?PHP
test class
{
    public function cool()
    {
         retunr true;

    }
}

//Then calling it like this
$test = new test();
$test->cool();
?>

OR

<?PHP
test class
{
    public static function cool()
    {
         retunr true;

    }
}

//Then calling it like this
test::cool();

?>

I realize this is the most basic example imaginable and the answer probably depends on the situation but maybe you can help me understand a little better

+1  A: 

Think of classes like 'blueprints' to an object. you want to use the static method when it is a general function that could apply to anywhere, and use methods when you want to reference that specific object.

GSto
Almost gave you +1, but... "you want to use the static method when it is a general function that *always applies the same* to any object". @too much php's answer was better -- if you need to access `$this`, it's not static.
Josh
+2  A: 

For your example, it is better to use a static function, but most situations will not be so simple. A good rule of thumb to start with is that if a method doesn't use the $this variable, then it should be made static.

too much php
+1  A: 

Here is an article that discusses differences in performance between these concepts: http://www.webhostingtalk.com/showthread.php?t=538076.

Basically there isn't any major difference in performance, so then the choice is made based on your design.

If you are going to create an object several times, then obviously a class makes sense.

If you are creating a utility function that isn't tied to a particular object, then create a static function.

James Black
I don't think we need to speak of performance in such a case. Running after the performance in such simple cases almost always damages a style of programming and makes your code smell badly.
FractalizeR
I just thought it was interesting that there isn't really any difference, and, it does help to know if there was going to be a big penalty using one or the other, to help make some decisions.
James Black