PHP function return value disappears (?) - php

In the following function call the log files show me that
even though before the return call the variable has a value the variable receiving the return value is empty
the if empty has just been included because I didn't believe what is happening.
What am I missing? Any clou?
...
...
$workingProductArray=$this->placeNextItem($workingProductArray, ... );
if (empty($workingProductArray)){
write_log ("DYING array empty");
die(); //<-- and indeed the system dies.
}
}
private function placeNextItem(array $workingProductArray, ... )
{
if ($this->areAllProductsIgnored($workingProductArray)){
print_r($workingProductArray); // <-- SHOWS EXPECTED ARRAY AND VALUES
return $workingProductArray; // returning this value
}

Weird! Try to not print_r2 from placeNextItem function if still doesn't work try to name $workingProductArray to something else for placeNextItem.

I was just digging into the code. and I just noticed I made a terrible thinking mistake...
(which you can't see on the mentioned code... here the code to the function's end)
...
...
$workingProductArray=$this->placeNextItem($workingProductArray, ... );
if (empty($workingProductArray)){
write_log ("DYING array empty");
die(); //<-- and indeed the system dies.
}
}
private function placeNextItem(array $workingProductArray, ... ){
if ($this->areAllProductsIgnored($workingProductArray)){
print_r($workingProductArray); // <-- SHOWS EXPECTED ARRAY AND VALUES
return $workingProductArray; // returning this value
}
...
$this->placeNextItem(array $workingProductArray, ...);
}
So I call this function also from within (recursively), I thought the return statement would go to the method above but instead it goes (doh! off course!) back to it's recursive caller, which is the same method where I have to return the value too...
easy fix:
private function placeNextItem(array $workingProductArray, ... ){
if ($this->areAllProductsIgnored($workingProductArray)){
print_r($workingProductArray); // <-- SHOWS EXPECTED ARRAY AND VALUES
return $workingProductArray; // returning this value
}
...
return $this->placeNextItem(array $workingProductArray, ...);
}

Related

Getting the return value from a function

Say I got some function that run some code and then return something, like this:
function something()
{
//some code
return $some[$whatever];
}
So, if I want to extract the data I generated in the function - the new value for $some, how should I do it? for example this won't do anything:
echo ($some);
Or what am I missing here, please
Since your Function returns a value, You may need to catch & store it inside a variable and then echo the variable if it is a String or do some casting to that effect. Here's an example:
<?php
function something(){
//some code
$whatever = 3;
$some = ["Peace", "Amongst", "All", "Humanity"];
return $some[$whatever];
}
$var = something();
var_dump($var); //<== DUMPS :: "Humanity"
echo $var; //<== ECHOES:: "Humanity"
Test it out here.
Cheers and Good Luck....
You are trying to return a specif key from your array, which wasn't declared. I declared an array for you, and I added the isset to check if the key is existing in the array to prevent any php warnings.
function something($findKey)
{
$some = array('key'=> 123);
if(!isset($some[$findKey])) {
return false;
}
//some code
return $some[$findKey];
}
echo something('key');

PHP array_map looping to itself

I´m creating an rest server using some examples in internet. The source is:
https://github.com/danucu/GUS/blob/master/restfulengine/restfulobj.php
The problem is when I´m making a call to the object, it calls itself again in the method getMyVars:
protected function getMyVars($myVars = null) {
if (empty($myVars)) {
$myVars = $this->showMyPublicsOnly();
}
if (is_array($myVars)) {
/*
* Intorc array convertit la obiect
* utilizand __METHOD__ (constanta ;) )
* pentru apelurile recursive
*/
return array_map(__METHOD__, $myVars);
} else {
// intorc array
return $myVars;
}
}
The full rest object is here:
https://github.com/danucu/GUS/blob/master/restfulengine/usertest.php
When Whe I run localhost/rest/UserREST/example it runs in a infinite loop.
I have changed the method getMyWars to:
echo $this->method."\n\n";
echo __METHOD__."\n\n";
$arReturn = array_map(__METHOD__, $myVars);
print_r($arReturn);
And I got:
GET
restObject::getMyVars
...infinitely and it never reaches: print_r($arReturn);
Maybe I´m doing something wrong.
Well, that code looks really strange, it will always call itself to the end of the times (or at least until the call stack overflows). Let me explain:
if (is_array($myVars)) { //is_array === true
return array_map(__METHOD__, $myVars); // This will call __METHOD__ (getMyVars); and pass $myVars to it (which is an array).
} else { //This will never be reached.
return $myVars;
}
Your code apparently works. What I think is happening is this:
first call: getMyVars() get passed, say, null.
this is empty, so it gets $this->showMyPublicsOnly()
this is an array, so every member of that array gets applied getMyVars()...
...but one of those values is equivalent to empty.
So if you have, say,
[ 'varOne' => 'Hello', 'varTwo' => 'World', 'varThree' => 42 ];
it will work, but
[ 'varOne' => '', ]
will loop.
You can try this:
// Only iterate on non-empty values
$myVars = array_filter($myVars);
// If there are no non-empty values...
if (empty($myVars)) {
/* ...this would loop, so we return an empty array */
return [ ];
}
return array_map(__METHOD__, $myVars);

Recursive function in php storing results without using static

I wrote the following recursive function to keep looping through result looking for $result->pages->next and calling out to curl fetching the next page and aggregating the results. Finally it returns all results as a single object.
private function pager($result) {
static $all_results;
if(isset($result->pages->next) && !empty($result->pages->next)) {
$all_results[] = $this->get_curl_request($result->pages->next);
$this->pager(end($all_results));
} else {
return $all_results;
}
}
However I really don't like using static and it feels poorly implemented and a source of technical debt. What is a more elegant way to do this?
Update
Being called with:
return $this->pager($this->get_curl_request("https://api/request/here"));
Open to changing how it is called.
Try putting $all_result as second parameter like this and add return for this line: $this->pager(end($all_results), $all_results);
Code
private function pager($result, $all_results) {
if(isset($result->pages->next) && !empty($result->pages->next)) {
$all_results[] = $this->get_curl_request($result->pages->next);
return $this->pager(end($all_results), $all_results);
} else {
return $all_results;
}
}
The above code function will return the last updated array $all_results.
Example of use:
$pager_array = $this->pager($result, array());

When is it useful to use a PHP function that ends with return;

What are the best usages of functions that end with "return;" and what are the advantages of writing a function that ends this way?
Example:
function MyFunction() {
// (do something)
return;
}
Thank you
You shouldn't, I would always use return null; so that it is an explicit declaration of what is returned (even if it is null). I'm sure this is also in one of the PSR specs as well, but I don't know them well. To confirm that return; === return null;:
function test() {
return;
}
var_dump(test());
// NULL
As to when you would want to return null;..any function that returns something, should always return something. So maybe if you have a function that gathers and returns a value from a DB, and an error occurs:
public function retrieveData()
{
$data = DB::retrieve();
if(!$data) {
return null;
}
return $data;
}
However, a lot of functions that may have errors just return true/false on success or failure so you won't necessarily use this often.
My main point to drive home: if you don't want/need to return anything, don't return anything.
A return; says only "thats the end". Mostly useful in following examples:
function test($string) {
if(empty($string)) {
return; // If the variable is empty, then stop to work!
}
echo $string;
}
A simple example is that you can write a PHP function that spits out formatted HTML:
function printHeader($value)
{
echo "<h1>$value</h1>";
return;
}
However, since you are not returning anything, the return statement is unnecessary and can be left out.
If you are talking about a empty return;, I can think of one example, if you have code that should be executed under a condition, and more code that should be executed if that condition is not met.
function MyFunction() {
if(a < 1) {
// (do something)
return;
}
// If a >= 0 it executes the code above and the code below
// Do something else
}

PHP Function Argument Default Value

Hey all.
I have a processForm function and a displayForm function. If there are missing form fields the processForm function returns an array of missing fields. This is all fine and dandy until I try to include this array into the displayForm function. Here's the problem:
If I don't do this:
displayForm($missingFields=array());
then my validateField function throws a warning that it is expecting the parameter to be an array. However, this overwrites the array returned by the processForm function.
I hope I'm clear. Thanks for any help.
Full Code:
if(isset($_POST['action']) && $_POST['action'] = "login")
{
$messages = processForm();
}
processForm()
if($errorMessages)
{
return array("errors" => $errorMessages, "missing" => $missingFields);
}
else
{
$_SESSION['user'] = $user;
header("Location: index.php");
}
form.php
(!isLoggedIn())? displayForm($messages['errors']=array(),$messages['missing']=array()) : null;
These are the sections of the code I'm having trouble with.
Thanks again.
You don't set default argument values in the call, you set them in the signature, for example
function displayForm($arg1 = array()) {
...
}
When you write
displayForm($messages['errors']=array())
this is actually doing something like this
$messages['error'] = array(); // set $messages['error'] to an empty array
displayForm($messages['error']); // pass an empty array to displayForm
This is because in PHP, the return value from an assignment is the value assigned.
Why are you using this:
displayForm($messages['errors']=array(),$messages['missing']=array())
When you writing "$messages['errors']=array()", this is setting $messeges to blank array. So the parameter is blank. You can just write:
displayForm($messages['errors'],$messages['missing'])

Categories