【问题标题】:How do I bind a closure to a static class variable in PHP?如何将闭包绑定到 PHP 中的静态类变量?
【发布时间】:2020-03-10 15:14:14
【问题描述】:
<?php

class A
{
    public $closure;

    public static function myFunc($input): string
    {
        $output = $input . ' is Number';
        return $output;
    }

    public static function closure(): Closure
    {
        return function ($input) {
            return self::myFunc($input);
        };
    }

    public static function run()
    {
        $closure = self::closure();
        echo $closure(1); // 1 is Number

        self::$closure = $closure;
        echo self::$closure(2); // Fatal error
    }
}

A::run();

我想将self::closure() 绑定到self::$closure,并在内部使用它,但它在某处消失了。如何在 PHP 中将闭包绑定到静态类变量?

【问题讨论】:

    标签: php static closures bind


    【解决方案1】:
    • 将您的属性更改为静态static $closure;
    • 将您的可调用对象括在括号中(self::$closure)(2);

    http://sandbox.onlinephpfunctions.com/code/d41490759cac39b8459e396b3acf99bf22c65a68

    <?php
    
    class A
    {
        static $closure;
    
        public static function myFunc($input): string
        {
            $output = $input . ' is Number';
            return $output;
        }
    
        public static function closure(): Closure
        {
            return function ($input) {
                return self::myFunc($input);
            };
        }
    
        public static function run()
        {
            $closure = self::closure();
            echo $closure(1); // 1 is Number
    
            self::$closure = $closure;
    
            // Wrap your callable in brackets
            echo (self::$closure)(2); 
        }
    }
    
    A::run();
    

    【讨论】:

      【解决方案2】:

      有2个问题:

      缺少static

      public <strong>static</strong> $closure;

      缺少括号:

      echo <b>(</b>self::$closure<b>)</b>(2);


      <?php
      
      class A
      {
          public static $closure;
      
          public static function myFunc($input): string
          {
              $output = $input . ' is Number';
              return $output;
          }
      
          public static function closure(): Closure
          {
              return function ($input) {
                  return self::myFunc($input);
              };
          }
      
          public static function run()
          {
              $closure = self::closure();
              echo $closure(1); // 1 is Number
      
              self::$closure = $closure;
              echo (self::$closure)(2); // 2 is Number
          }
      }
      
      A::run();
      

      【讨论】:

        猜你喜欢
        • 2014-03-05
        • 1970-01-01
        • 1970-01-01
        • 2010-12-06
        • 2014-11-09
        • 1970-01-01
        • 2013-11-22
        • 2013-05-27
        • 2011-02-11
        相关资源
        最近更新 更多