Is it better to use an object or a static function in PHP?

I am trying to learn OO and classes and all those good things in PHP, I am finally learning sytax well enough to use it, and I am curious if there is any benefit to starting a new object rather than just using static methods .. . let me show the code 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 simplest example imaginable, and the answer probably depends on the situation, but maybe you can help me understand a little better.

+2


source to share


3 answers


For your example, it's better to use a static function, but most situations won't be that easy. A good rule of thumb to start with is that if a method does not use a variable $this

, then it should be static.



+3


source


Think of classes like "blueprints" of an object. you want to use a static method when it is a generic function that can be applied anywhere, and use methods when you want to refer to that specific object.



+1


source


Here's an article that discusses the performance differences between the two: http://www.webhostingtalk.com/showthread.php?t=538076 .

Basically, there is no significant performance difference, so the choice is made based on your design.

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

If you are creating a utility function that is not bound to a specific object, create a static function.

+1


source







All Articles