As far as I understood it is already not possible languages like Java
, C#
etc. Because the method name of defining constructor in these languages must be same with the class name. That because I'll talk about PHP
which creating the constructor is more abstracted from the class name.
public function __construct(Type1 $arg1, Type2 $arg2)
{
...
}
Basically it is possible in PHP
to enforce construction
in interface
.
interface MyInterface {
public function __construct(Type1 $arg1, Type2 $arg2);
public function method1(Type3 $arg1) : Type3;
}
class MyClass implements MyInterface {
public function __construct(Type1 $arg1, Type2 $arg2)
{
// Implementation.
}
public function method1(Type3 $arg1) : Type3
{
// implementation
}
}
$object = new MyClass(new Type1(), new Type2());
So basically it works. If I try to define constructor
implementation different than the interface
basically it gives me the type error. Which is very nice you can enforce object construction
behaviour with a contract
. But I haven't seen this practise in other OOP
Languages what I mean Java
is more OOP than PHP
and it dominates the OOP world.
So here some of my questions :
- Is that practise has some pitfalls that I don't see ?
- There is nothing stated this situation in manual or I haven't seen yet.
Is this may be a harmless bug in PHP
?
Basically when we go through inheritance if we enforce the construction of a class then it also enforces the sub classes constructors or have same signature. Otherwise there is only function overload is possible with constructors in PHP
. It just blocks this behaviour and can harm extensibility over inheritance.
But also final
keyword aims to finalize inheritance so enforcing them for final classes and/or the classes that we don't want to let overload it's constructors? Do you think is this a good idea ?
I would like to hear some ideas and clarification I may abusing the behaviour I like to understand clearly.