programing

PHP 5.4 - 'closure $this support'

luckcodes 2023. 7. 22. 15:55

PHP 5.4 - 'closure $this support'

PHP 5.4의 새로운 계획된 기능은 특성, 어레이 역참조, JsonSerializable 인터페이스 및 '라고 하는 것입니다.closure $this support'

http://en.wikipedia.org/wiki/Php#Release_history

다른 것들은 즉시 명확하거나(Json Serialable, Array dereferencing) 세부 사항(특성)을 찾아봤지만, 'closure $this support'가 무엇인지 잘 모르겠습니다.저는 그것을 검색하거나 php.net 에서 그것에 대한 어떤 것도 찾지 못했습니다.

이게 뭔지 아는 사람?

제가 추측해야 한다면, 그것은 다음과 같은 것을 의미할 것입니다.

$a = 10; $b = 'strrrring';
//'old' way, PHP 5.3.x
$myClosure = function($x) use($a,$b)
             {
                 if (strlen($x) <= $a) return $x;
                 else return $b;
             };

//'new' way with closure $this for PHP 5.4
$myNewClosure = function($x) use($a as $lengthCap,$b as $alternative)
                 {
                     if(strlen($x) <=  $this->lengthCap)) return $x;
                     else 
                     {
                         $this->lengthCap++;  //lengthcap is incremented for next time around
                         return $this->alternative;
                     }
                 };

중요한 것은 (이 예가 사소한 경우에도) 과거에는 폐쇄가 일단 구성되면 경계된 '사용' 변수가 고정된다는 것입니다.'closure $this support'를 사용하면 그들은 당신이 엉망으로 만들 수 있는 회원에 더 가깝습니다.

이 소리가 올바르거나 닫히거나 합리적입니까?이 'closure $this support'가 무엇을 의미하는지 아는 사람이 있습니까?

이것은 이미 PHP 5.3용으로 계획되었지만,

PHP 5.3$의 경우 클로저에 대한 이 지원은 건전한 방식으로 구현하는 방법에 대한 합의에 도달할 수 없었기 때문에 제거되었습니다.이 RFC는 다음 PHP 버전에서 구현할 수 있는 가능한 방법을 설명합니다.

실제로 객체 인스턴스(라이브 데모)를 참조할 수 있음을 의미합니다.

<?php
class A {
  private $value = 1;
  public function getClosure() 
  {
    return function() { return $this->value; };
  }
}

$a = new A;
$fn = $a->getClosure();
echo $fn(); // 1

자세한 내용은 PHP Wiki를 참조하십시오.

그리고 역사적인 관심을 위하여:

고든이 놓친 한 가지는 다음과 같은 것입니다.$this그가 설명한 것이 기본 동작이지만 다시 바인딩할 수 있습니다.

class A {
    public $foo = 'foo';
    private $bar = 'bar';

    public function getClosure() {
        return function ($prop) {
            return $this->$prop;
        };
    }
}

class B {
    public $foo = 'baz';
    private $bar = 'bazinga';
}

$a = new A();
$f = $a->getClosure();
var_dump($f('foo')); // prints foo
var_dump($f('bar')); // works! prints bar

$b = new B();
$f2 = $f->bindTo($b);
var_dump($f2('foo')); // prints baz
var_dump($f2('bar')); // error

$f3 = $f->bindTo($b, $b);
var_dump($f3('bar')); // works! prints bazinga

폐점bindTo인스턴스(instance) 메서드(또는 정적 메서드 사용)Closure::bind)가 포함된 새 마감을 반환합니다.$this지정된 값으로 다시 바인딩됩니다.두 번째 인수를 전달하여 범위를 설정합니다. 이는 폐쇄 내에서 액세스할 때 개인 및 보호된 구성원의 가시성을 결정합니다.

@Gordon의 답변을 바탕으로 PHP 5.3에서 클로저 $의 일부 진부한 측면을 모방할 수 있습니다.

<?php
class A
{
    public $value = 12;
    public function getClosure()
    {
        $self = $this;
        return function() use($self)
        {
            return $self->value;
        };
    }
}

$a = new A;
$fn = $a->getClosure();
echo $fn(); // 12

여기에 있는 다른 답변을 바탕으로, 이 예는 PHP 5.4+가 가능한 것을 보여줄 것이라고 생각합니다.

<?php

class Mailer {
    public    $publicVar    = 'Goodbye ';
    protected $protectedVar = 'Josie ';
    private   $privateVar   = 'I love CORNFLAKES';

    public function mail($t, $closure) {
        var_dump($t, $closure());
    }
}

class SendsMail {
    public    $publicVar    = 'Hello ';
    protected $protectedVar = 'Martin ';
    private   $privateVar   = 'I love EGGS';

    public function aMailingMethod() {
        $mailer = new Mailer();
        $mailer->mail(
            $this->publicVar . $this->protectedVar . $this->privateVar,
            function() {
                 return $this->publicVar . $this->protectedVar . $this->privateVar;
            }
        );
    }
}

$sendsMail = new SendsMail();
$sendsMail->aMailingMethod();

// prints:
// string(24) "Hello Martin I love EGGS"
// string(24) "Hello Martin I love EGGS"

참조: https://eval.in/private/3183e0949dd2db

언급URL : https://stackoverflow.com/questions/5734011/php-5-4-closure-this-support