search

Home  >  Q&A  >  body text

How to get internal variables outside method body in PHP?

1. Source code:

    public function importexcel(Request $request){
        $file = Input::file('myfile');
        if($file->isValid()){
            $tmpName = $file->getClientOriginalName();
            $path = $file->move(storage_path().'/uploads',$tmpName);
            $subtmpName = substr($tmpName,0,-5);

            $filePath = "storage/uploads/".iconv('UTF-8', 'UTF-8', $subtmpName).'.xlsx';

            Excel::load($filePath, function($reader) {
                $reader->noHeading();
                $data = $reader->toArray();
                for($i = 1;$i<count($data);$i++){
                     $midArr = $data[$i];
                     //获取一个人员的Player_id字段
                     if($i == 1){
                         $first_player_id = $data[1][0];
                     }
                     for($j = 0;$j<count($midArr);$j++){                   
                          $player_id = (string)$midArr[0];
                          $node = (string)$midArr[1];
                          $childnode = (string)$midArr[2];
                          $time = (string)$midArr[3];
                         $uuid = (string)UUID::generate();
                         //将Excel表中的数据导入score表中
                        ***$result =  DB::insert('insert into score (id,player_id,node,childnode,time) values (?,?,?,?,?)',[$uuid,$player_id,$node,$childnode,$time]);***
                     
                     }
                }
            });
        }else{
            //Excel数据不合法的情况
        }

        dd($result);
    }
    

2. Question: How can the variable $result (italic) in the function body be called outside the method body, that is, the code dd($result)?

Solution: Reference:

<?php
class demo{
    public $var1 = null;
    public function func1(){
        $this->var1 = 'from func1';
    }
 
    public function func2(){
        echo $this->var1;
    }
}
$demo = new demo();
$demo->func1();
$demo->func2();

Defining variables in the class can be solved. The disadvantage is that all methods in the class can be accessed. I hope that the variable only exists in the body of the method importexcel(), and the variable $return in Excel::load($filePath, function($reader) {} can be accessed outside Excel::load().

过去多啦不再A梦过去多啦不再A梦2746 days ago657

reply all(2)I'll reply

  • PHPz

    PHPz2017-05-19 10:10:55

    $result = Excel::load($filePath, function($reader) {

    $result = array();
    .....
    $result[] =  DB::insert('insert into score (id,player_id,node,childnode,time) values (?,?,?,?,?)',[$uuid,$player_id,$node,$childnode,$time]);
    }
    }
    return $result;

    reply
    0
  • PHPz

    PHPz2017-05-19 10:10:55

    return $result, directly access the importexcel class from the outside. Since your $result result is logically generated by the importexcel function, direct access is not recommended

    reply
    0
  • Cancelreply