PHP Nesneler ve Kilitler

0 Cevap php

Geçenlerde bu konuyla ilgili bir kaç soru soran oldum, bu yüzden uygun ilgili soru (lar) kadar bağlantı hissediyorum.

http://stackoverflow.com/questions/4054424/php-closures-and-implicit-global-variable-scope

Kendime soru işlevlerine $obj argümanı geçen içerir (akılda ben hızlı bu iş parçacığı için birlikte bu örneği delikli) aşağıdaki örnekte olduğu gibi kapakları kullanabileceğiniz sınıfları bir dizi var.

Her türlü orada var mı magic değişkeni (cough-$this-öksürük ) that would permit me to access the object it's called from, instead of needing to declare a placeholder argument of $obj veya her neyse? Belki oynanırsa ettik, ama ben arayan kulüpler işlevselliği olan görünür en azından bağlamında, kaldırılmış $this.

class Test{

    private $_color;
    protected $_children = array();

    public function __construct(Closure $function){
        $function($this);
    }

    public function create(Closure $function){
        return new self($function);
    }

    public function color($color){
        $this->_color = $color;
        return $this;
    }

    public function add(Closure $function){
        $this->_children[] = new Test($function);
        return $this;
    }

}

Test::create(function($obj){
    $obj->color('Red')
        ->add(function(){
             $obj->color('Green');
        })
        ->color('Blue');
    });

Ben off-hand görebilirsiniz tek alternatif yaratılması her nesnenin bir örneğini depolanması, ve aşağıdaki gibi bir örneğini döndürmesi bir işlev sağlamaktadır:

class Test{

    private $_color;
    private static $_instance;
    protected $_children = array();

    public function __construct(Closure $function){
        self::$_instance = $this;
        $function();
    }

    .
    .
    .

    public static function this(){
        return self::$_instance;
    }

}

Test::create(function(){
    Test::this()
        ->color('Red')
        ->add(function(){
            Test::this()
                ->color('Green');
        })
        ->color('Blue');
    });

0 Cevap