0

In the application I am working on, there are some classes with only static functions.

These classes do not follow the Singleton pattern. Consider them just as "tools".

Not real example:

class MathHelper {
    public static function plus($num1, $num2)
    {
        return $num1 + $num2;
    }
}

Would it be good practice to forbid the construction with ...

    private function __construct()
    {
    }

just to prevent such class to be instantiated?

Hector Ordonez
  • 1,044
  • 1
  • 12
  • 20

3 Answers3

0

You could define the class as abstract to prevent instantiation.

abstract class MathHelper {
    public static function plus($num1, $num2)
    {
        return $num1 + $num2;
    }
}

echo MathHelper::plus(1,2); // 3
$math = new MathHelper(); // Fatal error: Cannot instantiate abstract class MathHelper
Ian Brindley
  • 2,197
  • 1
  • 19
  • 28
0

declare the constructor as private, and don't define the function. Clause 6 of book 《effective C++》 talks about this.

class MathHelper {
public:
    static function plus($num1, $num2)
    {
    return $num1 + $num2;
    }
private:
    MathHelper ();
}
0

Like @ian-brindley answered, you could prevent instantiation by declaring your class abstract but if you also want to declare that class also as final you can omit the abstract and throw an excption in the constructor:

<?php
final class MyClass
{
  public function __construct()
  {
    throw new \Exception();
  }
}
Jens Kohl
  • 5,899
  • 11
  • 48
  • 77