Program Tip

PHP 5.4- '$ this 지원 종료'

programtip 2020. 11. 7. 10:23
반응형

PHP 5.4- '$ this 지원 종료'


PHP 5.4에 대한 새로운 계획 기능은 특성, 배열 역 참조, JsonSerializable 인터페이스 및 ' closure $this support'

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

다른 것들은 즉시 명확하거나 (JsonSerialiable, 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'로 그들은 당신이 엉망이 될 수있는 회원들과 비슷합니다.

이 소리가 정확하고 /하거나 가깝거나 합리적입니까? 이 '폐쇄 $ 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를 참조하십시오.

역사적 관심사 :


Gordon이 놓친 한 가지는 $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

The closures bindTo instance method (alternatively use the static Closure::bind) will return a new closure with $this re-bound to the value given. The scope is set by passing the second argument, this will determine visibility of private and protected members, when accessed from within the closure.


Building on @Gordon's answer it is posible to mimic some hacky aspects of closure-$this in 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

Just building on the other answers here, I think this example will demonstrate what is possible 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"

see: https://eval.in/private/3183e0949dd2db

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

반응형