Вопрос по php, micro-optimization – Как мне вернуть несколько переменных в функцию (для передового опыта)?

12

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

function myfun(){

global $var1,$var2,$var3;

$var1="foo";
$var2="foo";
$var3="foo";

}//end of function

Error: User Rate Limit Exceeded

function myfun(){

$var1="foo";
$var2="foo";
$var3="foo";

$ret_var=array("var1"=>$var1,"var2"=>$var2,"var3"=>$var3);

return $ret_var;

}//end of function

Error: User Rate Limit Exceeded

array took: 5.9999999999505E-6
global took: 2.0999999999938E-5

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded jrennie
Error: User Rate Limit ExceededmaintainError: User Rate Limit Exceeded webbiedave
Error: User Rate Limit Exceeded Felix Kling
Error: User Rate Limit Exceeded user849137
Error: User Rate Limit Exceeded Manos Dilaverakis

Ваш Ответ

6   ответов
2

5

function myfun(&$var1, &$var2, &$var3)
{
    $var1="foo";
    $var2="foo";
    $var3="foo";
}

AND NEVER USE GLOBALS!

2

function multiple() {
    return array('val1', 'anotherval');
}

list($var1, $var2) = multiple();

echo "$var1, $var2";

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
2

.

class Vari {
    var $var1;
    var $var2;
    var $var3;
}

function myfun() {    
    $var = new Vari;
    $var->var1="foo";
    $var->var2="foo";
    $var->var3="foo";
    return $var;    
}

$v = myfun();
echo $v->var1;
/*foo*/
2

  function  myFunction() {

      //your code that returns your results to variables below

     $var1 = 'message 1';
     $var2 = 'message 2';
     $var3 = 'message 3';

     // must put all variables inside an array to get them outside of function
     $return_array = ($var1, $var2, $var3);

     // return your array inside function
     return $return_array;
  }



 // call function (returns all variables in array)
 $get_results = myFunction();

 // call and assign individual variables outside of function
 $var1 = $get_results[0];
 $var2 = $get_results[1];
 $var3 = $get_results[2];



 // now you can use individual variables outside of function for example:

 echo $var2;   //will now output: message 2
 echo $var3;   //will now output: message 3

  //original code to change
  function  myFunction() {
  //change to
  function  myFunction($db) {

  //original code to change
  $get_results = myFunction();
  //change to
  $get_results = myFunction($db);
19

list

function foon() {
   return array('one', 'two', 'three');
}
list($one, $two, $three) = foon();

Error: User Rate Limit Exceeded

Похожие вопросы