Last active
December 19, 2015 08:19
-
-
Save leonnguyen/5925162 to your computer and use it in GitHub Desktop.
PHP Closure example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| header('Content-Type: text/plain;charset=UTF-8'); //utf-8 character with content type has html (e.g Vietnamess) | |
| /** | |
| * Closure example | |
| * | |
| **/ | |
| /* #1: a sample closure without param */ | |
| $helloworld = function() {echo "hello world !"; }; | |
| $helloworld(); | |
| echo "\n----------------------------------------------\n"; | |
| /* #2: closure with param */ | |
| $hello = function($message) { echo $message; }; | |
| $hello("xin chào thế giới !"); | |
| echo "\n----------------------------------------------\n"; | |
| /* #3: closure use external variable */ | |
| $name = "Nguyễn Văn Tèo"; | |
| $print_myname = function() use ($name) { | |
| $name = $name . " hello there !"; | |
| echo $name; | |
| }; | |
| $print_myname(); | |
| echo "\n"; | |
| echo $name; //variable not change after used by closure | |
| echo "\n----------------------------------------------\n"; | |
| /* #4: Closure also can change external variable */ | |
| $total = 0; | |
| $subTotal = function() use (&$total) { | |
| return $total = 30000*365; | |
| }; | |
| echo $subTotal(); | |
| echo "\n"; | |
| echo $total; | |
| echo "\n----------------------------------------------\n"; | |
| /* #5: Closure inside an object */ | |
| /** | |
| * Student class | |
| */ | |
| class Student { | |
| private $_studentName; | |
| private $_studentNumber; | |
| function __construct($name, $number) { | |
| $this->_studentName = $name; | |
| $this->_studentNumber = $number; | |
| } | |
| public function show_info($greeting_message) { | |
| $result = function() use ($greeting_message) { | |
| return "$greeting_message ! \n Student Number: {$this->_studentNumber} \n Student Name: {$this->_studentName}"; | |
| }; | |
| return $result(); | |
| } | |
| } | |
| $nvteo = new Student("Nguyễn Văn Tèo", "1081433"); | |
| echo $nvteo->show_info("Xin chào sinh viên"); | |
| echo "\n----------------------------------------------\n"; | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment