Skip to content

Instantly share code, notes, and snippets.

@leonnguyen
Last active December 19, 2015 08:19
Show Gist options
  • Select an option

  • Save leonnguyen/5925162 to your computer and use it in GitHub Desktop.

Select an option

Save leonnguyen/5925162 to your computer and use it in GitHub Desktop.
PHP Closure example
<?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