简体   繁体   中英

Avoid running function more than once

Hi what would be a better way to write the following code so myScript() isn't executed several times?

<?php

function myScript($myVar){
  //some code
  return $anotherVar;
}

$data = myScript("some input");
echo $data.$data.$data;

$data变量仅存储输出,当您回显变量时不会多次执行。

In your script the function execute only once. you use the return value more and more.

The function never run alone, it is you who can call for a function to run.

function myScript($myVar){
  return $anotherVar; //5
}

$data = myScript("some input");
echo $data.$data.$data; //555

You can also call this function multiple time if you want different values for different parameter like:

function myScript($myVar){
  return $myVar * $myVar;
}

$data1 = myScript(3);
$data2 = myScript(4);
$data3 = myScript(5);
echo $data1." - ".$data2." - ".$data3; //9 - 16 - 25

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM