PHP functions, a very simple way to prevent repetitive code and save you time.
An example of a PHP function:
function test($a, $b){ $var = $a + $b; return $var; } echo test('10', '30');//40 echo test('22', '14');//36
Here we made or defined a function called test which has two inputs variable a and b. Inside the function we have a variable var that is what a + b equals. This is then returned. Note that all functions must have a return, the return can be empty though. The function test can be called, echo’d of assign to a variable and as you see from the 2 example echos using functions is a space saver (and this is only a mini simple function!).
PHP 7.4 brings type declarations:
function footerText(string $text, int $year) { return "$text. copyright $year"; }
As well as return type hints:
function doCalc(int $start, int $finish): int { return ($start * ($start + $finish)); }
Functions that I find handy with API calls are ones that return arrays. That way you can make just one API call and store several bits of data in an array rather than doing multiple calls and using up your api limits.
//Array function function array($id, $api_key){ $data = json_decode(file_get_contents("https://exampleapicall.com/profiles&id=".$id."&key=".$api_key.""),true); $name = $data->name; $email = $data->email; $score = $data->score; $joined = $data->joined; return array('name' => $name, 'email' => $email, 'score' => $score, 'joined' => $joined); } $jims_data = array('1952', '4678hcxhjg6d78fyh'); echo $jims_data['name'];//Jim echo $jims_data['score'];//1138 $jims_name = $jims_data['name']//asigns jims name to a variable
Here the function requires the id of the profile we want to query and the API key. We then pack what we need from the JSON into an array to store. When we need to access jims data we just call $jims_data['KEY']