Reputation: 48933
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
Upvotes: 2
Views: 298
Reputation: 41858
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.
Upvotes: 1
Reputation: 90978
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.
Upvotes: 3
Reputation: 42350
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.
Upvotes: 1