PHP constructors

Asked

Viewed 283 times

1

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

2 answers

4

Since PHP is a dynamic language, method overload is not necessary. Programming in PHP as if it were in C# does not make sense. even so almost everyone has tried to do. If it is to program as in C#, then use C#.

Creating contract engines like the ones PHP has made available in newer versions doesn’t make any sense in dynamic language, so it causes confusion in people.

The solution in this case is to create a constructor with all parameters and internally treat the cases of parameters that have not been used and establish what to do. Something you can do in C# as a build engine, obviously with limitations. In PHP it solves me running time, 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, then you can have as many as you want, each with a different name, and you can choose how the parameters of each one will be and how they build the object. Therefore 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 code called.

But then why is there a constructor in the language? Why create a pseudo overload in a language that chose 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);

I put in the Github for future reference.

  • I get it, I’m studying php a little while ago, I came from C# so I’m trying to adapt

1


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

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

And to use it:

User::create($data);

Non-statically:

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

$user = new User();

$user->create($data);
  • 2

    I may be wrong because the question is not so clear, but I don’t think that’s what he wants to know.

  • That’s what it was all about

Browser other questions tagged

You are not signed in. Login or sign up in order to post.