user2507818
user2507818

Reputation: 3037

When is necessary to use static methods?

I thought usually we use static method because we do not need to instantiate objects. and we can use className::staticFunction to call static method, bub today found:

test1.php

<?php
class Foo { 
    static public function helloWorld() {
        print "Hello world " ;
    }
}
Foo::helloWorld();

test2.php

<?php
class Foo { 
    public function helloWorld() {
        print "Hello world " ;
    }
}
Foo::helloWorld();

Question:

Both of above scripts work. We did not declare function as static, we can still use className::staticFunction to call the function. Why do we need use static methods?

Upvotes: 4

Views: 768

Answers (6)

Ja͢ck
Ja͢ck

Reputation: 173522

We did not declare function as static, we can still use className::staticFunction

What you probably didn't notice is that PHP complains about the second type of invocation:

PHP Strict Standards: Non-static method Foo::helloWorld() should not be called statically in php shell code on line 1

Strict Standards: Non-static method Foo::helloWorld() should not be called statically in php shell code on line 1

To make these notices visible you need to set the value of error_reporting to -1, either using ini_set() or via the php.ini configuration file; btw, this is recommended during development.

Conclusion

A function that's called statically should be declared as static function xyz().

Update

Btw, using the scope resolution operator :: doesn't necessarily mean you're making a static call; consider this example:

class Foo 
{ 
    public function helloWorld() 
    {
        print "Hello world ";
    }

    public function doSomething()
    {
        self::helloWorld();
    }
}

$f = new Foo;
$f->doSomething();

This works because using self:: as opposed to Foo:: doesn't change the invocation "mode" (unless the method you're calling is defined as static).

Upvotes: 5

deceze
deceze

Reputation: 522005

The "problem" with static methods is the way they're called:

Foo::bar();

Any call to a static method is by necessity hardcoded and cannot easily be substituted. Compare with:

$foo->bar();

$foo is a variable here, meaning the exact object and implementation of bar() can be substituted. This is important for and the basis of dependency injection.

You'd use a static method for:

  • first and foremost cases where you don't need individual object instances
  • anything you need to do before an object can be instantiated
  • alternative object constructors, for instance DateTime::createFromFormat() instead of new DateTime
  • idempotent utility functions which you are 100% sure never need to be substituted or mocked

You may use static functions in other scenarios here and there, but these are the main points. You need to be aware that declaring a method static means you need to call it statically, which means its call-time use cannot really be altered. For a long treaty on this subject, read How Not To Kill Your Testability Using Statics.

Upvotes: 2

From the above example test1.php

helloworld() function cannot be overriden or overloaded since you have added a static keyword.

However in the second example, test2.php

helloworld() function can be overloaded and overriden

Illustration:1 (Works)

<?php
class Foo {
    function helloWorld() {
        print "Hello world " ;
    }
}

class Foo1 extends Foo
{
    function helloWorld()
    {
        echo "Foo's World";
    }
}
$Foo1 = new Foo1();
$Foo1->helloWorld(); //Foo's World

Illustration:2 (Fails)

Cannot make static method Foo::helloWorld() non static

<?php
class Foo {
    static function helloWorld() {
        print "Hello world " ;
    }
}

class Foo1 extends Foo
{
    function helloWorld()
    {
        echo "Foo's World";
    }
}
$Foo1 = new Foo1();
$Foo1->helloWorld();

Upvotes: 0

Prince Singh
Prince Singh

Reputation: 5183

When you are working on a large OOP based project, you’ll no doubt be working with many classes (both parent and child classes). An unfortunate consequence of this is that in order to access elements from different classes, they must manually be passed through each class (or worse, storing an instance in a global variable). This can be painstakingly frustrating and can lead to messy code and overall bad project design. Thankfully, static elements are accessible from any context (i.e. anywhere in your script), so you can access these methods without needing to pass an instance of the class from object to object.

As you don’t need to declare an object instance to access static elements, you can be saved from unnecessary declarations to access seemingly simple functions.

Static elements are available in every instance of a class, so you can set values that you want to be available to all members of a type.

Upvotes: 0

Phix
Phix

Reputation: 9880

PHP is funny like that, but I'll usually have a utilities class which takes arguments of things to perform logic on and return. Stuff like this doesn't need an instantiated class. It's up to the user/developer to correctly call methods (read: use the correct method accessors).

Upvotes: 0

DevZer0
DevZer0

Reputation: 13525

Well a simply hello world program might not be able to show a big difference is the usage of static vs not but take a look at this class

class foo {


    private $a = 1;

    private static $b = 2;


    public function foobar()
    {
        echo $this->a;
    }

}

in this above class if you call foobar statically then $this->a will not resolve.

Upvotes: 0

Related Questions