Functions Returning Different Data Types

CakePHP has a (fairly fundamental) method called find . In most cases, this method returned an array, but if you pass count as the first parameter, the method will return another data type - an integer.

The method allows you to return various types of data.

Isn't that so bad?

+4
source share
4 answers

Scripting languages ​​tend to use this pattern to return multiple types depending on any type of input parameter or parameter value.

This can be confusing, but as long as you have good documentation, this is not a problem and can be very powerful.

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

+1
source

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

+1
source

This is by design. PHP is a dynamically typed language, so you cannot defend against functions that return various data types (unlike Java, where you can be sure that a function returns). It is very flexible (but also bad), so it would be nice to prevent unexpected results by writing unit tests. You can see phpunit for the unit testing platform.

+1
source

Not bad as long as the behavior is documented . In C / C ++, for an example that is a strongly typed language, you can achieve a similar result using void ( void* ) pointers:

 // 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; } 

Then you can do the following:

 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, without documenting it correctly , unexpected behavior may occur . Because if the pointer should be distinguished as an unexpected type, then it is used:

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

The above compiles but does not execute at runtime. Of course, segfault will not do this in PHP, but it will likely ruin the rest of your program.

+1
source

Source: https://habr.com/ru/post/1337599/


All Articles