發表文章

正規表示式 (Regular Expression)

正規表示式 (Regular Expression) 能為你檢查是否為全英文字串! 很專業! 正規表示式 (Regular Expression) 能為你檢查是否為指定結構字串! 很貼心! 正規表示式 (Regular Expression) 能為你找出複雜性組成字串! 很厲害!

PHP Closure(閉包、匿名函式)

PHP Closure(閉包、匿名函式) 還不知道  PHP  有  Closure ? 那你真的落伍了! What is Closure? Closure: 用於表示 匿名函式 的  Class 。 閉包減少了 命名空間 的混亂。也讓使用對象之間減少了 相依性 。 PHP5.3  開始支援 匿名函式 ,讓一些需要彈性的場合更方便。 建立匿名函式 注意: 賦予變數 匿名函示 ,結尾大括號需要加結尾符號  ; 。 $wellcome = function () { echo 'Hi, wellcome to my Home '; }; $wellcome(); 我們可以透過 use 的宣告語法賦予匿名函式變數。 注意: PHP 7.1 起,不能傳入此類變數:superglobals、 $this 或者和參數重名。 $houseCategory = 'villa'; $wellcome = function () use ($houseCategory) { echo 'Hi, wellcome to my ' . $houseCategory . '.'; }; $wellcome(); 讓我們添加函式的指定參數 $houseCategory = 'villa'; $wellcome = function ($name) use ($houseCategory) { echo 'Hi ' . $name . ', wellcome to my ' . $houseCategory . '.'; }; $wellcome('YoYo'); 會使用了之後,我們馬上用遞迴特性寫一個從 1 加總到指定數字的閉包吧。 $fib = function ($n) use (&$fib) { if ($n == 0) { return 0; } return $n + $fib($n - 1); }; echo $fib(10); 小分享 筆者很常在  某段邏輯前後的行為  需要被重複使用時,使用閉包。 例如 sql 的  Transaction 。 此處程...

PHP Traits

What is Traits? PHP 僅支援單一繼承: 子類別只能繼承單一物件。 若是一個類需要繼承多種行為怎麼辦呢? Traits 解決了這個問題。 Traits 就是解決在單線繼承的限制下,讓程式碼能夠重複使用。並降低複雜度。 Traits 用於聲明可以在多個 class 中使用的屬性(property)/函式(function),可以是抽象或是任何可視性(public、protect 、private),甚至是靜態(abstract)屬性。 如何使用 建立語法 trait TraitName { // some code... } 使用語法 class newClass { use TraitName; } Example trait message { function msg() { echo 'Welcome to my home.'; } } class Welcome { use message; } $welcome = new Welcome(); $welcome->msg(); 可以同時使用多個 trait messageFriendly { function msg() { echo 'Welcome to my home.'; } } trait messageQuestion { function msgQuestion() { echo 'Why are you here?'; } } class Welcome { use messageFriendly, messageQuestion; } $welcome = new Welcome(); $welcome->msg(); echo '<br/>'; $welcome->msgQuestion(); 若是名稱重複了呢? 函式名稱重複是會造成錯誤的。 Fatal error: Trait method msg has not been applied, because there are collisions with oth...