开发者

Functions returning various data types

In CakePHP there is a (quite fundamental) method called find. Most of the time this method would return an array but if you pass count as the first parameter the method would 开发者_如何学Pythonreturn a different data type - an integer.

The method is allowed to return various data types.

Isn't that bad?


Scripting languages tend to use this pattern of returning multiple types depending on either type of input parameters or value of parameters.

It can be confusing, but as long as you have good documentation its not a problem and can be very powerful.

Strongly typed languages use function overloads to do the same thing.


No. It is a flexible way. In php standard functions return different types too. For example strpos(). It can return integer position and boolean false.


It's not a bad thing as long as the behaviour is documented. In C/C++ per example, which is a strongly-typed language, you can achieve a similar result by using void pointers (void*):

// returns a "const char*" if c == 0
// returns a "string*" if c == 1
const void* foo(int c) {
    const void* a;
    if (c == 0) {
        a = (const void*)"foo";
    } else if (c == 1) {
        string* b = new string("bar");
        a = (const void*)b;
    }
    return a;
}

You can then do this:

const char* x = (const char*)foo(0); // get a const char*
string* y = (string*)foo(1);         // get a string*
std::cout << x << *y;                // prints "foobar"

However, not documenting it properly may result in unexpected behaviour. Because if the pointer was to be cast as an unexpected type and then used:

string* y = (string*)foo(0);         // get a const char*, bad type cast
std::cout << *y;                     // Segmentation fault

The above compiles fine but fails at runtime. Of course, doing a similar thing in PHP will not segfault, but will most likely screw up the rest of your program.


This is by design. PHP is dynamically typed language, so you cannot guard yourself against functions that return various data types (unlike Java, where you can be sure what the function is returning). That's very flexible (but also can be bad) so it's a good idea to guard against unexpected results by writing unit tests. You can see phpunit for a Unit Testing framework.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜