note 124054 added to language.types.callable
| From: | gulaschsuppe2 at gmail dot com | Date: | Sun, 21 Jul 2019 13:53:26 +0000 |
| Subject: | note 124054 added to language.types.callable | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-211670@lists.php.net to get a copy of this message | ||
I tried many possible ways of calling functions by function name directly and assigned to a variable
on 3v4l. Not mentioned yet, it is possible to use an array as a caller, at least since PHP 7.1.25.
The following script contains all the information I gained:
<?php
// Call function via function name:
// Basics:
// A function can also be called by using its string name:
function callbackFunc() {
echo 'Hello World';
}
'callbackFunc'(); // Hello World
// A function can also be called if its name is assigned to a variable:
function callbackFunc() {
echo 'Hello World';
}
$funcName = 'callbackFunc';
$funcName(); // Hello World
// Static class method:
// It is also possible to call a public static class method via
'ClassName::functioName' notation:
class A {
public static function callbackMethod() {
echo "Hello World\n";
}
}
'A::callbackMethod'(); // Hello World
$funcName = 'A::callbackMethod';
$funcName(); // Hello World
// Non static class method:
// It is also possible to call non static class methods by creating an array which first
element is the object the method should be called on and the second element is the non static method
to be called. The array can directly be used as a caller:
class A {
private $prop = "Hello World\n";
public function callbackMethod() {
echo $this->prop;
}
}
$a = new A;
[$a, 'callbackMethod']();
$funcCallArr = [$a, 'callbackMethod'];
$funcCallArr();
// Of course this also works inside the class with '$this':
class A {
private function privCallback() {
echo 'Private';
}
public function privCallbackCaller($funcName) {
[$this, $funcName]();
}
}
(new A)->privCallbackCaller('privCallback'); // Private
?>
----
Server IP: 208.43.231.9
Probable Submitter: 185.85.3.195 (proxied: 2a02:8109:dc0:a4:80ad:44e4:5fb4:d313)
----
Manual Page -- http://php.net/manual/en/language.types.callable.php
Edit -- https://master.php.net/note/edit/124054
Del: integrated -- https://master.php.net/note/delete/124054/integrated
Del: useless -- https://master.php.net/note/delete/124054/useless
Del: bad code -- https://master.php.net/note/delete/124054/bad+code
Del: spam -- https://master.php.net/note/delete/124054/spam
Del: non-english -- https://master.php.net/note/delete/124054/non-english
Del: in docs -- https://master.php.net/note/delete/124054/in+docs
Del: other reasons-- https://master.php.net/note/delete/124054
Reject -- https://master.php.net/note/reject/124054
Search -- https://master.php.net/manage/user-notes.php