Mixed Results for Class Method
I use PHP with the Codeigniter framework, and often have methods in my classes that return an array of values. It makes things simpler in my views if there are no records returned, that the method return FALSE or NULL, rather than returning an empty array. In my views I can just have something like:
<?php if($abc_array) : ?>
// loop through the array, etc.
<?php else : ?>
// show some message
<?php endif; ?>
If I return an empty array, I end up including something like the following in the views:
<?php if(is_array($abc_array) AND count($abc_array) > 0) : ?>
I guess this is kind of a trivial example, but I'm mainly wondering if it is considered bad practice to have class methods return mixed result types. What about if a mysql error is somehow generated in the class and caught, should I have the returned result types something like:
FALSE (o开发者_Go百科n some type of error)
Empty Array (if no results were returned)
Array of Results (results were returned)
I'm just trying to figure out what the best practices are for this kind of thing...
You can always throw exceptions, and wrap your code in try/catch blocks. This is what you'll find most database abstraction classes like PDO actually do.
精彩评论