andyjdavis
andyjdavis

Reputation: 349

In php is there a reason to use a static method on a class instead of an independent method?

We're having this discussion here. Which is better and why?

1) a php file that just includes a function...

function bar(){}

called like this

bar();

2) a php that contains a class with a static method.

class foo{
static function bar(){}
}

called like this foo::bar();

Are there any performance reasons to do one or the other? For code organization purposes the static method looks better to me but there are a few programmers here who see no reason to declare classes.

Upvotes: 2

Views: 515

Answers (2)

Amber
Amber

Reputation: 527328

I'd say the main advantage is the reuse-ability and modularity aspect - what if you have two different "libraries" of functions you've created A and B, and they both happen to have bar() functions? As static methods, you can call A::bar() and B::bar(), but as independent functions you'd have name conflicts.

Sure, you can get around this by putting weird prefixes on all your independent function names to make it unlikely that names will conflict, but if you're going to do that, it's a lot simpler to just wrap it in a class and use them as static functions.

In PHP 5.3+ you can also use namespaces to accomplish this purpose if you so desire.

Upvotes: 6

VolkerK
VolkerK

Reputation: 96159

For organizational purposes namespaces have been added to php 5.3+.

Static methods have access to protected/private members of an object of that class. e.g.

class Foo {
  protected function xyz() {
    return 'abc';
  }

  public static function bar(Foo $f) {
    echo $f->xyz();
  }
}

$f = new Foo;
Foo::bar($f);

And you can use the same visibility options to share static properties between different methods of the same class but protect them from the "outside". E.g.

class Foo {
  protected static $abc;

  public static function set($x) {
    self::$abc = $x*2;
  }

  public static function get() {
    return self::$abc;
  }

}
Foo::set(1);
echo Foo::get();

Upvotes: 2

Related Questions