I donβt know why, but I donβt like using the new operator in my code.
Here is a static function to instantiate a class called statically.
class ClassName { public static function init(){ return (new ReflectionClass(get_called_class()))->newInstanceArgs(func_get_args()); } public static function initArray($array=[]){ return (new ReflectionClass(get_called_class()))->newInstanceArgs($array); } public function __construct($arg1, $arg2, $arg3){
If you use it inside a namespace, you need to avoid the ReflectionClass as follows: new \ ReflectionClass ...
Now you can call the init () method with a variable number of arguments and pass it to the constructor and return the object for you.
The usual way using the new
$obj = new ClassName('arg1', 'arg2', 'arg3'); echo $obj->method1()->method2();
Built-in method using the new
echo (new ClassName('arg1', 'arg2', 'arg3'))->method1()->method2();
Static call using init instead of new
echo ClassName::init('arg1', 'arg2', 'arg3')->method1()->method2();
Static call using initArray instead of new
echo ClassName::initArray(['arg1', 'arg2', 'arg3'])->method1()->method2();
The good thing about static methods is that you can run some pre-build operations in init methods, such as checking constructor arguments.
Dieter gribnitz
source share