开发者

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

开发者 https://www.devze.com 2022-12-21 05:35 出处:网络
We\'re having this discussion here. Which is better and why? 1) a php file that just includes a function...

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.


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.


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消