PЯINCƎ
PЯINCƎ

Reputation: 724

PHP Call function once and get the first result

For the php pro guys, what is the best practice for this scenario :

I have some function with two params consult($id, $value), this function save that id and value in some database then returns me some codes :

C1 = value has well been saved,

C2 = there is already an entry with this value !

I call my function like this :

$id = "10";
$value = "ABCD";
$save = $block->consult($id, $value);

Then I get the result like this :

echo $save->{'return'}->result; // return C1 or C2

Now I think when I call $save = $block->consult($id, $value); It execute the function once, and when I echo $save->{'return'}->result; It execute it once again.

I thought about doing this to execute the function just once and print the result :

$block->consult($id, $value)->{'return'}->result;

With this it execute the function and return the result just one time, what do you think, is there a better idea ?

Upvotes: 0

Views: 153

Answers (2)

Dipti
Dipti

Reputation: 565

when I echo $save->{'return'}->result; It execute it once again.

It will not execute consult function i.e $save = $block->consult($id, $value);

Please return function result in array or json format and Print_r result. It will give result of first execution call. if you call second time then it will give another id. Until and unless it will not execute two times. Your are accessing return result variable values.

Upvotes: 1

seravee
seravee

Reputation: 434

function consult($id, $value){

// your functionality 
 $res  = ''; // Store the return response and return it.
 return $res;
}

In your calling should be

$id = "10";
$value = "ABCD";
$result = $block->consult($id, $value);
echo $result;

Upvotes: 0

Related Questions