I'm trying to figure out what's better approach for argument passing to the class methods / standard functions.
Basically - if we use default null for each argument then we can validate them from within the method and throw an exception, but if we do not assign any default value to them and no argument has been passed when the method is called it will throw an Error.
My question is - which one is the more 'correct' approach:
public function getOne($id = null) {
if (empty($id)) {
throw new Exception('Method '.__METHOD__.' failed : invalid argument');
}
// throws an exception if no argument is passed
}
vs:
public function getOne($id) {
// throws an error if no argument is passed
}
The first approach allows me to catch the exception and return relevant output, wheres (and I might be wrong here) Error does not provide this sort of functionality.
Also - is it better to hint object instance arguments with the class name or pass it as standard argument and check whether it's an instance of the given object - pretty much same situation:
public function getOne($mdlUser = null) {
if (
is_object($mdlUser) &&
$mdlUser instanceof 'UserModel'
) {
throw new Exception('Method '.__METHOD__.' failed : invalid argument');
}
// throws an exception if no argument is passed
}
vs:
public function getOne(UserModel $mdlUser) {
// throws an error if no argument is passed
}
I would like to hear some opinions / facts including pros and cons of both.