note 125038 added to functions.variable-functions
| From: | Anonymous@php.net | Date: | Sat, 23 May 2020 05:26:42 +0000 |
| Subject: | note 125038 added to functions.variable-functions | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-214665@lists.php.net to get a copy of this message | ||
If you are here looking for a function reference, this is NOT how to do it:
<?php
function func1(){ echo "hell0 1";}
$choice = func1; // no quotes
?>
It works, but $choice is not what you might think, a reference to a function. It is simply the name
of the function as a string, written without (!) quotes.
It's the same as
<?php
$choice = "func1"; // with quotes
?>
You can do echo gettype($choice) to confirm.
So calling
<?php
$choice()
?>
is a variable-function for both cases, calling it by its name, not by reference.
Go via an assigned anonymous function to get a reference to the function:
<?php
$func1 = function(){ echo "hell0 1";}
$func1 = function(){ echo "hell0 2";}
?>
Now you can pass around the function like a first class object
<?php
$choice = $func1;
?>
or
<?php
$choice = $func2;
?>
and call it
<?php
$choice();
?>
If you want to pass around a class method, use the "Complex callables" from the manual,
above. It's a call by name (not a reference), but since you can include the object you can
still get the flexibility you want:
<?php
class C {
function k(){ echo "inside k";}
function j(){ echo "inside j"; return array($this,"k");}};
?>
You can use $this as the object in the first element of the array.
<?php
$c = new C;
$c->k();
inside k
$func = $c->j();
inside j
?>
And now, le moment supreme:
<?php
$func();
inside k
?>
----
Server IP: 45.112.84.4
Probable Submitter: 103.51.166.36 (proxied: 2001:569:72cc:6100:9434:6ea4:699b:430c)
----
Manual Page -- http://php.net/manual/en/functions.variable-functions.php
Edit -- https://master.php.net/note/edit/125038
Del: integrated -- https://master.php.net/note/delete/125038/integrated
Del: useless -- https://master.php.net/note/delete/125038/useless
Del: bad code -- https://master.php.net/note/delete/125038/bad+code
Del: spam -- https://master.php.net/note/delete/125038/spam
Del: non-english -- https://master.php.net/note/delete/125038/non-english
Del: in docs -- https://master.php.net/note/delete/125038/in+docs
Del: other reasons-- https://master.php.net/note/delete/125038
Reject -- https://master.php.net/note/reject/125038
Search -- https://master.php.net/manage/user-notes.php