PHP, as we all know is very loosely typed. The language does not require you to specify any kind of type for function parameters or class variables. This can be a powerful feature.
Sometimes though, it can make debugging your script a painful experience. For example, passing one kind of object into a method that expects a different kind of object can produce error messages complaining that a certain variable/method doesn't exist for the passed object. These situations are mostly annoyances. More onerous problems are when you initialize one object with an object of the wrong class, and that "wrong object" won't be used until later on in the script's execution. In this case you end up getting an error much later than when you passed the original argument.
Instead of complaining that what I passed doesn't have a specific method or variable, or waiting until much later in script execution for my passed in object to be used, I would much rather have an error message, at exactly where I specify an object of the wrong type, complaining about the object's type being incorrect or incompatible.
How do you handle these situations in your code? How do you detect incompatible types? How can I introduce some type-checking into my scripts so that I can get more easily understood error messages?
Also, how can you do all this while accounting for inheritance in Php? Consider:
<?php
class InterfaceClass
{
#...
}
class UsesInterfaceClass
{
function SetObject(&$obj)
{
// What do I put here to make sure that $obj either
// is of type InterfaceObject or inherits from it
}
}
?>
Then a user of this code implements the interface with their own concrete class:
<?php
class ConcreteClass extends InterfaceClass
{
}
?>
I want ConcreteClass instances, and all future, unknown user-defined objects, to also be acceptable to SetObject. How would you make this allowable in checking for the correct type?