iT邦幫忙

2021 iThome 鐵人賽

DAY 5
0
自我挑戰組

PHP 與 Laravel 雜記系列 第 5

PHP 一些特性

Closure 類、匿名函數

Closure class用來表示匿名函數 (anonymous function), PHP 5.3 開始支持,

<?php 
/*
class Closure {
  private __construct()
  public static bind(Closure $closure, ?object $newThis, object|string|null $newScope = 'static'): ?Closure
  public bindTo(object $newthis, object|string|null $newScope = 'static'): ?Closure
}
bind: 複製一個 closure 綁定指定的 $this 和類作用域, 第一個參數是需要綁定的匿名函數, 第二個參數是要指定的 $this, 第三個參數是想要綁定給 closure 的類作用域, 'static' 表示不改變, 如果傳入一個物件則使用這物件的類型名, 類作用域用來決定 closure 中 $this 物件的屬性可見性
bindTo: 複製當前 closure 綁定指定的 $this 和類作用域
*/
class A{
  private static $_cat = 'cat';
  private $_dog = 'dog';
  public $pig = 'pig';
}

$cat = function() {
  echo A::$_cat;
};

$dog = function() {
  echo $this->_dog;
};

$pig = function() {
  echo $this->pig;
};

$bindCat = Closure::bind($cat, null, 'A');
$bindDog = Closure::bind($dog, new A(), 'A');
$bindPig = Closure::bind($pig, new A());
$bindCat();
echo "\n";
$bindDog();
echo "\n";
$bindPig();
echo "\n";

匿名函數

<?php
// 匿名函數, 定義一個函數體, 將函數體賦值給一個變數
$func = function() {
  echo "this is a function\n";
};

$func1 = function($param) {
  var_dump($param);
};
// 將匿名函數作為參數傳入
function dFunc($func, $param) {
  $func($param);
}

dFunc($func1, '123');

// 定義一個函數, 在該函數中將內部的匿名函數返回
function cFunc($param) {
  $func = function($param1) use ($param) {
    echo "param:".$param1." ".$param;
  };
  
  return $func;
}

$rFunc = cFunc("123");
$rFunc("456");

變數的可視範圍(variable scope)

區域變數(local variable)
在 function 中宣告, 可視範圍在 function 內, 不需使用任何關鍵字, 函數執行結束後就消失
全域變數(global variable)
在 function 外宣告, 整個檔案可視, 但在 function 內使用要使用 global 關鍵字, 註明使用 global 變數

<?php
$a = 1;
$b = 2;
include 'b.inc';  // $a 也會在 b.inc 裡可用

function Test() {
  global $a;   // 使用 global 變數 $a
  echo $a;
}
Test();

// 或使用超全域(superglobal)變數 $GLOBALS, 一個包含全部變數的的全域組合陣列, 變數名就是 key
function Test2() {
  echo $GLOBALS['b'];
}
Test2();

靜態變數(static variable)
只存在於函數中, 但函數執行結束後不會消失

<?php
function test() {
  static $a = 0;
  echo $a;
  $a++;
}
test();
test();

上一篇
PHP 一些概念
下一篇
PHP array 相關函數
系列文
PHP 與 Laravel 雜記14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言