Skip to content

Instantly share code, notes, and snippets.

@Ultimater
Created August 2, 2018 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ultimater/f23749cc68f58d6015b4fceb6404c848 to your computer and use it in GitHub Desktop.
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
<?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();
@Ultimater
Copy link
Author

Run as either php -S localhost:8000 test-it.php or php 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment