PHP閉包之bind和bindTo


PHP閉包之bind和bindTo

Closure類摘要如下:

Closure {  
    __construct ( void )  
    public static Closure bind (Closure $closure , object $newthis [, mixed $newscope = 'static'] 
    public Closure bindTo (object $newthis [, mixed $newscope = 'static' ])
}

方法說明:

Closure::__construct — 用於禁止實例化的構造函數
Closure::bind — 復制一個閉包,綁定指定的$this對象和類作用域。
Closure::bindTo — 復制當前閉包對象,綁定指定的$this對象和類作用域。

閉包之bind方法

一個實例

<?php
/** 
 * 復制一個閉包,綁定指定的$this對象和類作用域。 
 * 
 * @author 瘋狂老司機 
 */
class Animal {
    private static $cat = "cat";
    private $dog = "dog";
    public $pig = "pig";
}

/* 
 * 獲取Animal類靜態私有成員屬性
 */
$cat = static function() {
    return Animal::$cat;
};

/* 
 * 獲取Animal實例私有成員屬性
 */
$dog = function() {
    return $this->dog;
};

/* 
 * 獲取Animal實例公有成員屬性
 */
$pig = function() {
    return $this->pig;
};

$bindCat = Closure::bind($cat, null, new Animal());// 給閉包綁定了Animal實例的作用域,但未給閉包綁定$this對象
$bindDog = Closure::bind($dog, new Animal(), 'Animal');// 給閉包綁定了Animal類的作用域,同時將Animal實例對象作為$this對象綁定給閉包
$bindPig = Closure::bind($pig, new Animal());// 將Animal實例對象作為$this對象綁定給閉包,保留閉包原有作用域
echo $bindCat(),'<br>';// 根據綁定規則,允許閉包通過作用域限定操作符獲取Animal類靜態私有成員屬性
echo $bindDog(),'<br>';// 根據綁定規則,允許閉包通過綁定的$this對象(Animal實例對象)獲取Animal實例私有成員屬性
echo $bindPig(),'<br>';// 根據綁定規則,允許閉包通過綁定的$this對象獲取Animal實例公有成員屬性

總結:

  • bind函數:
    • 參數1($closure) : 表示閉包函數
    • 參數2($newthis): 相當於在函數內/外調用的區別,傳類的實例表示在內部調用,NULL相當於在外部調用
    • 參數3($newscope): 相當於類和實例調用的區別,函數的作用域, 傳類表示靜態調用方式,內部可以“類名::屬性”的方式使用;實例表示實例調用方式,內部可以“->”


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM