how to define function name (in PHP) using variable, like this?
$a='myFuncion';
function $a() {.......}
or like that?
The only way I know to give a fixed name to a function is to use eval, which I would not suggest.
More likely, what you want is to stuff a function IN a variable, and then just call that.
Try this:
$a = function() {
echo 'This is called an anonymous function.';
}
$a();
EDIT:
If you want to be accessible from other files, then use GLOBAL variable:
$GLOBALS['variable_name'] = 'my_func_123';
${$GLOBALS['variable_name']} = function() {
echo 'This is called an anonymous function.';
};
// Executing my_func_123()
${$GLOBALS['variable_name']}();
See also: http://php.net/manual/en/functions.anonymous.php
Related
So I basically want to do this:
$this->container['Menu_builder'] = $this->container->factory(function ($c) {
return new Menu_builder($parameter_1, $parameter_2);
});
Where $parameter_1 and $parameter_2 are passed in from the call, like this:
$menu_builder = $this->container['Menu_builder']('account', 'reset_password');
I know the above syntax is incorrect, but I want to pass these strings into the call to $this->container->factory.
Is this possible?
For example, if I wanted to instantiate the Menu_builder from various controller functions with different parameters for each controller function.
FWIW, you can also include an anonymous function within your container.
$this->container['Menu_builder'] = function() {
// do stuff here
return function($parameter_1, $parameter_2) {
return new Menu_builder($parameter_1, $parameter_2);
};
};
Use this way:
$localfunc = $this->container['Menu_builder'];
$result = $localfunc($parameter_1, $parameter_2);
Notice that in this case I'm not using a factory. That's because you can execute the anonymous function with different values each time.
You just can use use() to pass your variables to the anonymous functions, e.g.
//your parameters needs to be defined here:
$parameter_1 = "XY";
$parameter_2 = 42;
$this->container['Menu_builder'] = $this->container->factory(function ($c)use($parameter_1, $parameter_2) {
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ See here
return new Menu_builder($parameter_1, $parameter_2);
});
I am looking for a way to test if a variable is an anonymous function/callback. Using the PHP.net example:
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
You could call it with:
$greet('hi');
But what if $greet could be some other variable type and you only want to execute the callback if it's set to a function? Something like:
is_func($greet);
is_callback($greet);
is_callable($greet);
Am I missing something in the documentation?
is_callable($greet) will do that.
Also:
($greet instanceof Closure) might work.
Is there any way to do this / specify this in the php.ini configuration file? It would be really nice, at least for local server purposes, just to write functions without having to write the global keyword every time a global variable is used within the method.
Any way to do this?
EDIT:
What I mean is being to simply write this:
Example file "index.php":
$MY_ARRAY = array();
include("functions.php");
And then in "functions.php":
function addToArray($pMessage) {
$MY_ARRAY[] = "<a href='somelink.php'>$pMessage</a>";
}
Instead of:
And then in "functions.php":
function addToArray($pMessage) {
global $MY_ARRAY;
$MY_ARRAY[] = "<a href='somelink.php'>$pMessage</a>";
}
Yeah! You can setup a prepend file in PHP.
See: http://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
I still do not understand the purpose. But if I need to just remove the GLOBAL keyword from mentioning everytime, I would prefer to use a class with static array.
Something like this:
<?php
// Config.php
class Config {
public static $MY_ARRAY = array();
}
?>
And then include this file from your loader just call like this:
function addToArray($pMessage) {
Config::$MY_ARRAY[] = "<a href='somelink.php'>$pMessage</a>";
}
That will work.
In JavaScript, you can define anonymous functions that are executed immediately:
(function () { /* do something */ })()
Can you do something like that in PHP?
For versions prior to PHP 7, the only way to execute them immediately I can think of is
call_user_func(function() { echo 'executed'; });
With current versions of PHP, you can just do
(function() { echo 'executed'; })();
In PHP 7 is to do the same in javascript
$gen = (function() {
yield 1;
yield 2;
return 3;
})();
foreach ($gen as $val) {
echo $val, PHP_EOL;
}
echo $gen->getReturn(), PHP_EOL;
The output is:
1
2
3
This is the simplest for PHP 7.0 or later.
(function() {echo 'Hi';})();
It means create closure, then call it as function by following "()". Works just like JS thanks to uniform variable evaluation order.
https://3v4l.org/06EL3
Well of course you can use call_user_func, but there's still another pretty simple alternative:
<?php
// we simply need to write a simple function called run:
function run($f){
$f();
}
// and then we can use it like this:
run(function(){
echo "do something";
});
?>
(new ReflectionFunction(function() {
// body function
}))->invoke();
Note, accepted answer is fine but it takes 1.41x as long (41% slower) than declaring a function and calling it in two lines.
[I know it's not really a new answer but I felt it was valuable to add this somewhere for visitors.]
Details:
<?php
# Tags: benchmark, call_user_func, anonymous function
require_once("Benchmark.php");
bench(array(
'test1_anonfunc_call' => function(){
$f = function(){
$x = 123;
};
$f();
},
'test2_anonfunc_call_user_func' => function(){
call_user_func(
function(){
$x = 123;
}
);
}
), 10000);
?>
Results:
$ php test8.php
test1_anonfunc_call took 0.0081379413604736s (1228812.0001172/s)
test2_anonfunc_call_user_func took 0.011472940444946s (871616.13432805/s)
This isn't a direct answer, but a workaround. Using PHP >= 7. Defining an anonymous class with a named method and constructing the class and calling the method right away.
$var = (new class() { // Anonymous class
function cool() { // Named method
return 'neato';
}
})->cool(); // Instantiate the anonymous class and call the named method
echo $var; // Echos neato to console.
I tried it out this way, but it's more verbose than the top answer by using any operator (or function) that allows you to define the function first:
$value = $hack == ($hack = function(){
// just a hack way of executing an anonymous function
return array(0, 1, 2, 3);
}) ? $hack() : $hack();
Not executed inmediately, but close to ;)
<?php
$var = (function(){ echo 'do something'; });
$var();
?>
There is basic persistence of Javascript vars/etc. You call a function/method, and the next time you call that same function/method, it is holding the data from the last time.
You can delete the vars when you are done with them, but that removes the advantage of using the code again for that instance.
So what is the proper way to write code which can be reused, on different elements, inside the same page.
Therefore, I need the ability to write code so that I can point it at several different elements, and then interact with that code segregated for each element.
So in PHP (as an example) I would do:
$element1 = new MyClass();
$element2 = new MyClass();
$element3 = new MyClass();
in that case it's the same code running in three segregated scopes. How can I do this properly with JS. Even using jQuery's extend() gives me problems.
Thanks.
Use the var keyword when defining local variables (otherwise they'll default to globals).
function foo() {
var i;
// code code code code
}
To create an instance in JavaScript you need to write a constructor function, and call that using new. For instance:
function MyClass( somevalue ) {
this.somevalue = somevalue;
this.somefunction = function() {
alert(somevalue);
}
}
var instance1 = new MyClass(1);
var instance2 = new MyClass(2);
var instance3 = new MyClass(3);
You can namespace your JavaScript to make it a lot like what you're after. See below for an example. It does sound like your problem is related to using global variables where you want to use local variables though - i.e. you declare var myvariable; outside of your function, but only want to use it and forget it within your function. In that case, declare the variable inside your function to make it local.
var MyNameSpace = function() {
return {
sayhello : function() {
alert("hello");
},
saygoodbye : function() {
alert("see ya");
}
};
}();
It sounds like what you're looking for is the ability to have instances of a class and have private data that's associated with each instance.
You can do this using the following technique:
function Foo()
{
// Member variable only visible inside Foo()
var myPrivateVar;
// Function only visible inside Foo()
var myPrivateFunction = function()
{
alert("I'm private!");
}
// Member variable visible to all
this.myPublicVar = "Hi, I'm public!";
// Function visible to all
this.myPublicFunction = function()
{
myPrivateVar = "I can set this here!";
}
}
You can create and use one of these using the following syntax:
var myFoo = new Foo();
myFoo.myPublicVar = "I can set this!";
myFoo.myPublicFunction();