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.
In this specific case there is no advantage or disadvantage. However, a static method can be used by other static methods (perhaps some
public staticmethod). Are you sure it’s not called by another static method?Technically any method that has no reliance on
$thiscan be static as long as it conforms to its interface (e.g. if a parent method relies on$thisbut the child method doesn’t, the child method should not be static).