Created
August 2, 2018 04:07
-
-
Save Ultimater/f23749cc68f58d6015b4fceb6404c848 to your computer and use it in GitHub Desktop.
Response to "Store function expression to a variable in PHP inside a class" stackoverflow question
This file contains 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 | |
class Demo | |
{ | |
static public $var; | |
public $a; | |
public function __construct() | |
{ | |
$this->a = function() | |
{ | |
return 'hello there'; | |
}; | |
} | |
public function a() | |
{ | |
return 'hello world'; | |
} | |
} | |
// You can store information directly on the class via static | |
// Otherwise anything else is stored in the instance of the class, not the class directly. | |
Demo::$var = function(){ return 'hello internets'; }; | |
// Not sure if we're running via terminal/CLI/console or an HTML browser | |
// So assume terminal, and make the browser accept raw text instead of HTML. | |
header('Content-Type: text/plain'); | |
$x = new Demo; | |
echo ($x->a)(); // hello there | |
echo "\n"; | |
echo $x->a(); // hello world | |
echo "\n"; | |
echo (Demo::$var)(); // hello internets | |
// Just to show you this can all be assigned to a variable of its own and accessed as variables without parentheses | |
list($a,$b,$c) = [$x->a, function() use($x){return call_user_func_array([$x,'a'],func_get_args());},Demo::$var]; | |
echo "\n\n"; | |
echo $a(); | |
echo "\n"; | |
echo $b(); | |
echo "\n"; | |
echo $c(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run as either
php -S localhost:8000 test-it.php
orphp test-it.php
from your terminal.If running the first way, access as http://localhost:8000/ in your browser.
Otherwise, the output will display directly in your terminal.