Lets say I create and interface
interface IMyInterface {
function abstractMethod();
}
class MyClass implements IMyInterface {
function abstractMethod() {
//code
}
}
class OtherClass {
private $IMyInterfaceObj;
function __construct($obj) {
$this->IMyInterfaceObj = $obj;
}
}
What can I do to make sure that the object assigned to $IMyInterfaceObj is an Object that actually implements the interface, since PHP is loosely typed. Should I check the type???
You would type hint it in the constructor. You cannot do this for basic types such as integers or strings, although you can for arrays with array
. The only value you can use to make a parameter an optional one is to use null
.
class OtherClass {
private $IMyInterfaceObj;
function __construct(IMyInterface $obj) {
$this->IMyInterfaceObj = $obj;
}
}
Thoroughly reading the documentation on interfaces and type hinting should clear anything else up on the subject.