不要将$ this传递给匿名函数的范围

时间:2017-03-23 03:40:37

标签: php

有没有办法不将类传递给匿名函数?

    <?php
        $connect = mysqli_connect("localhost","root", "","nets") or die("Couldn't connect to database");        
        $query = mysqli_query($connect,"SHOW columns FROM users");
          while($row = $query->fetch_assoc()) {
                if( (strcmp($row['Field'],"Name") !== 0) ||
                    (strcmp($row['Field'],"ID") !== 0)||
                    (strcmp($row['Field'],"Password") !== 0)||
                    (strcmp($row['Field'],"Email") !== 0)||
                    (strcmp($row['Field'],"Company") !== 0)||
                    (strcmp($row['Field'],"Gender") !== 0)||
                    (strcmp($row['Field'],"Citizen") !== 0)){
            ?>
            <input type="radio" name="admin" value="'$row'"> 
                <?php
                    echo $row['Field'];
                    }
                ?>
                <br/>
            <?php
            }
            ?>   

我可以从匿名函数中排除$ this吗?

1 个答案:

答案 0 :(得分:2)

如果您不想要$this的值,则需要static anonymous function

class Foo{
  public function bar(){
     $data = [
        'calculation' => static function(){
           // $this is not defined
        }
     ];
  }
}

静态匿名函数没有自动绑定$this值,以后它们不能再绑定其他值。