Lizard
Lizard

Reputation: 45032

Static keyword usage php

Let say I have a class like the following:

class MyClass {
  public function __construct($str) {
    // do some stuff including:
    $str = self::getIP($str);
  }

  private static function getIP($str) {
    return (bool) ip2long($str) ? $str : gethostbyname($str);
  }

  // other NON static functions ....
}

In the above scenario what is the advantage/disadvantage of having getIP static vs simply:

private function getIP($str) {
  return (bool) ip2long($str) ? $str : gethostbyname($str);
}

and calling $this->getIP(); in the constructor (or any other method)

Context: I would normally do this without the static keyword but I have come across this a couple of times recently. Just wondering if there was any advantage of using static when you are definitely not going to use this.

Upvotes: 0

Views: 984

Answers (2)

David Grenier
David Grenier

Reputation: 1241

In this particular case I'm not sure. Usually I use static methods because:

  • It stores data in a static variable that I want accessible from several objects (sort of like a global)
  • I don't want to have to create an instance of the object every time I call that method - especially if it's mostly called from outside.

For example, I usually create an App object that has many helper methods. One of these is fetch_db. Every time I want to connect to the database I just call App::fetch_db().

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191799

In this specific case there is no advantage or disadvantage. However, a static method can be used by other static methods (perhaps some public static method). Are you sure it's not called by another static method?

Technically any method that has no reliance on $this can be static as long as it conforms to its interface (e.g. if a parent method relies on $this but the child method doesn't, the child method should not be static).

Upvotes: 1

Related Questions