Should my PHP functions actively return the "right" type?

php function return
php return
important php functions list pdf
php function return multiple values
how we can return multiple values from a function in php
get defined functions() 'internal'
php function return type
php function return array

I have made various functions such as "get_current_balance_from_my_bank_account()". It technically returns a string, but it's always a full integer number (as a string) which has never caused problems when its return variable is used directly in calculations.

However, it feels wrong.

Should I be doing something like this?

return (int)$amount_as_a_string;

Instead of the current:

return $amount_as_a_string;

? Or is (int) some archaic/legacy way of doing this? Should I be using some other, better method?

Example of the context:

$my_balance = get_current_balance_from_my_bank_account();
$previous_balance = load_last_balance();

echo 'I have ' . format_money_prettily($my_balance - $previous_balance) . '!' . PHP_EOL;

Again, I rarely if ever run into issues with this because it understands the "real" type. It does still feel wrong that I'm technically returning and sending around strings which in theory could be causing problems sooner or later -- perhaps catastrophic ones in production!

PHP will implicitly type cast in many situations, but not all. Take for example this:

echo json_encode(['balance' => get_current_balance_from_my_bank_account()]);

Now your type propagates to some other system via JSON, where it may cause actual issues if that system isn't so lenient about types. You're making somebody else deal with your incorrect type.

So, yes, your function should always return the type that it claims it returns. PHP implicitly "helping" you when you don't stick to your own type declarations is just sweeping the problem in the rug, but the problem is still there and may eventually cause actual issues.

Best practice with php functions is it best to use return or echo , get_defined_functions — Returns an array of all defined functions Whether disabled functions should be excluded from the return value. look at here, list all the defined function on your php-Version and give as well formatted output width links a:active { color: #444444; } a:hover { text-decoration: underline; } </ style> With regard to the Functions section, I wonder why it's better to return an variable rather than echo the results within the function? I have tried to apply the same technique to my own sample code below. My code works as seen here, but when I try to return a variable instead of echoing the results it outputs nothing to the screen.

I don't think that is something you have to worry to much, considering that php has automatic type conversion.

From the docs:

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used.

Just because the function returns the right data type does not mean that the value is correct or what you expect.

If you want to make sure that the function returns ok value, validating it before returning it much more helpful than simply typecasting it to correct type.

get_defined_functions - Manual, Note: If the return is omitted the value NULL will be returned. A function can not return multiple values, but similar results can be obtained by returning an array. Be careful about using "do this thing or die()" logic in your return lines. PHP 7 adds support for return type declarations. Similarly to argument type declarations , return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations. Strict typing also has an effect on return type declarations.

If you want to be more explicit about typing in PHP, have a look at the following from the manual:

default

By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.

Strict mode

It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float. Function calls from within internal functions will not be affected by the strict_types declaration.

To enable strict mode, the declare statement is used with the strict_types declaration:

<?php
declare(strict_types=1); // strict type declaration MUST be the very first statement in your script

function sum(int $a, int $b) {
    return $a + $b;
}

var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
?>

output

int(3)

Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given

Note: Enabling strict mode will also affect return type declarations.

source: php.net

Returning values - Manual, List of all the functions and methods in the manual. a b c d e f g h i j k l m n o p q r s t u v w x y z _ in which the messages from the DOMAIN message catalog will be returned; blenc_encrypt - Encrypt a PHP script Change logged in user of the active connection; fbsql_clob_size - Get the size of a CLOB; fbsql_close - Close� PHP User Defined Functions. Besides the built-in PHP functions, it is possible to create your own functions. A function is a block of statements that can be used repeatedly in a program. A function will not execute automatically when a page loads. A function will be executed by a call to the function.

This will never be required in PHP, as it does the type conversion by itself. However you can do this if you want. This depends from project to project, but sometimes a decision is made for a certain project to use explicit types where possible. Also this is a good practice if you are working on a team where some of the people are comfortable with more strict languages.

In your case, depending on the number, there might be a good side in keeping it as a string, as if you convert it to int via casting and the number is bigger than the max_int_size, it will overflow.

As for the other question, casting as int (int) or (integer) is a perfectly good way to do it, even in newer versions. It is not a legacy way whatsoever. This does not mean there aren't other good ways to do that, though. You can also use something like intval() or settype(). In my opinion there isn't one right way to do it. You can decide for yourself on how to do that.

Function and Method listing - Manual, If called from within a function, the return statement immediately ends execution then the value given to return will be returned as the value of the include call. Caution: Functions should not start with __ (double underscore) character, since, the PHP magic functions are starts with this characters for example __clone (). A Function with a return type must return any value. Otherwise, an error will occur on execution.

return - Manual, The above code assumes that if $_POST['active'] returns true , then postData PHP Notice: Undefined index: test in /path/to/my/script.php on line 21 This means that a copy of the array will be returned and therefore the called function and� Function-return value in PHP. A function can return a value using the return statement in conjunction with a value or object. In return value function, return keyword is used to return a value from a function. In return value function, return stops the execution of the function and sends the value back to the calling code.

The List of the 10 Most Common Mistakes That PHP Developers , From your WordPress dashboard, navigate to XYZ PHP Code In this example, we will add the date() function that returns the local For future use, make sure all the PHP functions you want to use are active by checking the� This line of the code calls the function. $ php simple.php this is PHP 5.5.9-1ubuntu4.14 Here we see the outcome of the script. PHP return keyword. The return keyword is used to return a value from the function. A function may or may not return a value.

How to Add PHP Code to A WordPress Post or Page, And if PHP can't access the target MySQL server at all then it is also smart enough to issue the appropriate error all The mysql_fetch_[row|object|array] functions return data as type string. I edited the php.ini-recommended, renamed it to just php, added my sql username, database name, etc. Active Persistent Links 0 The void type can never be part of a union. As such, types like T|void are illegal in all positions, including return types.. The void type indicates that the function has no return value, and enforces that argument-less return; is used to return from the function.

Comments
  • it won’t be required since PHP does implicit type conversion.
  • its a matter of "taste". strings give more control as they can be casted the required type.
  • No. But your coworkers will expect you to do so.