Installation:
composer require scriptfusion/static-class
Add the StaticClass trait to your class:
use ScriptFUSION\StaticClass\StaticClass;
class MyStaticClass
{
use StaticClass;
public static function myStaticMethod()
{
return 'Hello, Static World!';
}
}
First Use Case:
StringHelper, ArrayHelper, Logger).$result = MyStaticClass::myStaticMethod(); // Works
$instance = new MyStaticClass(); // Throws \RuntimeException
Where to Look First:
__construct() override.Enforcing Static Design:
Config, Route, or custom helpers).class DatabaseHelper
{
use StaticClass;
public static function sanitizeInput(string $input): string
{
return filter_var($input, FILTER_SANITIZE_STRING);
}
}
Integration with Laravel:
// app/Providers/AppServiceProvider.php
public function boot()
{
app()->singleton('staticHelper', function () {
return new class {
use StaticClass;
public static function greet() { return 'Laravel!'; }
};
});
}
// app/Facades/StaticHelper.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class StaticHelper extends Facade
{
protected static function getFacadeAccessor() { return 'staticHelper'; }
}
Testing:
partialMock in PHPUnit:
$mock = $this->getMockBuilder(MyStaticClass::class)
->setMethods(['myStaticMethod'])
->getMock();
$mock->method('myStaticMethod')->willReturn('Mocked!');
RuntimeException by extending the trait:
class CustomStaticClass
{
use StaticClass {
__construct as private __staticConstruct;
}
public function __construct()
{
throw new \InvalidArgumentException('Cannot instantiate!');
}
}
Instantiation Attempts:
RuntimeException if instantiation is attempted. Catch this explicitly in tests or edge cases:
try {
new MyStaticClass();
} catch (\RuntimeException $e) {
$this->assertStringContainsString('Cannot instantiate', $e->getMessage());
}
Static Method Limitations:
$this or instance properties. Design classes to avoid stateful logic.app()->make()) unless explicitly needed.Facade Confusion:
__construct() will still block it. Use debug_backtrace() to trace the origin:
public function __construct()
{
throw new \RuntimeException(
'Cannot instantiate ' . static::class .
'. Called from: ' . print_r(debug_backtrace(), true)
);
}
__construct() method.Add Static Properties:
class MathUtils
{
use StaticClass;
private static $pi = 3.14159;
public static function calculateCircleArea(float $radius): float
{
return self::$pi * pow($radius, 2);
}
}
Laravel-Specific Use:
ShouldBeStatic trait (if available) or use this trait in phpstan/psalm configurations to enforce static-only classes in static analysis tools. Example psalm.config.php:
return [
'properties' => [
'ScriptFUSION\StaticClass\StaticClass' => [
'properties' => [],
],
],
];
How can I help you explore Laravel packages today?