2

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

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Seems like a great rule of thumb especially with regards to testability of code.
1

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.

1 Comment

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

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.

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.