PHP builders [closed]

1

Can not create 2 constructors for a class. How do I instantiate a class and use its functions without having to create a new object? In C #, for example, I use an empty constructor and I can still use one with parameters.

    
asked by anonymous 14.06.2018 / 19:25

2 answers

1

The only way to use the methods of a class without instantiating it is if they are static . Example:

class User 
{
    public static function create($data)
   {
     // code here
   }
}

And to use it:

User::create($data);

Non-static:

class User
{
    public function create($data)
   {
     // code here
   }
}

$user = new User();

$user->create($data);
    
14.06.2018 / 19:35
4

Because PHP is a dynamic language, methods overloading is not necessary. Programming in PHP as if programming in C # does not make sense. even so almost everyone has tried to do. If it's to program like in C #, then use C #.

Creating contract mechanisms like the one PHP has made available in later versions makes no sense in dynamic language, so it causes confusion in people.

The solution in this case is to create a constructor with all the parameters and internally to handle the cases of parameters that were not used and to establish what to do. Something you can do in C # as a compilation engine, obviously with limitations. In PHP it solves itself at runtime, so it is more flexible.

class Classe {
    pubclic function __construct($p1, $p2) {
        if (!isset($p2)) $p2 = 10;
        //inicialza o objeto aqui
    }
}

Another possibility is to create a static method that does the construction, there you can have as many as you want, each one with a different name, and you can choose how they will be the parameters of each one and how they construct the object. So you have a function in the class that does not depend on the instance that will create an instance internally and return that created object to your called code.

But why there is a constructor in language? Why create a pseudo overhead in a language that has chosen not to have this?

class Classe {
    public static function create($par) {
        return new Classe($par, 10);
    }
    pubclic function __construct($p1, $p2) {
        //inicialza o objeto aqui
    }
}

$obj = Classe::create($data);
    
14.06.2018 / 19:59