I have a string variable
$worker_name = "video_convert"
I want to write a function with the name like the following
function video_convert(){
}
How can I do this in PHP? I tried
function eval($worker_name){
}
or
eval($worker_name) = function(){
}
But, it seems like it is not the correct way to do it in PHP.
You can do it as
$worker_name = 'video_convert';
$$worker_name = function() {
echo 'hi';
};
$$worker_name();
You could use call_user_func :
$worker_name ="video_convert"
function video_convert($text){
echo "Hello $text\n";
}
call_user_func($worker_name, 'World');
OR you could use the way you tried:
$worker_name = 'video_convert';
function video_convert(){
echo __METHOD__;
}
$worker_name();
OR like this:
$worker_name = function($text)
{
echo 'Anonymous function call '.$text
};
$worker_name('Hello');
PHP is flexible.
You can do somewhat like as
$worker_name = "video_convert";
function video_convert(){
echo "I've called a function using variable";
}
$worker_name();
If you want to use eval() function then use it by below way:-
$worker_name = "video_convert()";
function video_convert(){
echo "Called";
}
eval("$worker_name;");
Related
I'm trying to achieve almost similar things/properties of closure in PHP which is available in JS.
For example
function createGreeter($who) {
return function(){
function hello() use ($who) {
echo "Hi $who";
}
function bye() use($who){
echo "Bye $who";
}
};
}
I know my syntax is incorrect, this what I'm trying to achieve.
What I've done so far is.
function createGreeter() {
$hi = "hi how are you.";
$bye = "bye wish you luck.";
return function($operation) use ($hi, $bye){
if ($operation == "a") return $hi;
elseif ($operation == "b") return $bye;
};
}
$op = createGreeter();
echo $op("a"); #prints hi how are you.
echo $op("b"); #prints bye wish you luck.
Please look does PHP allows us to do this.
You could return an anonymous class which is created with the $who and then has methods which output the relevant message...
function createGreeter($who) {
return new class($who){
private $who;
public function __construct( $who ) {
$this->who = $who;
}
function hello() {
echo "Hi {$this->who}";
}
function bye(){
echo "Bye {$this->who}";
}
};
}
$op = createGreeter("me");
echo $op->hello(); // Hi me
echo $op->bye(); // Bye me
Decided to post as a new answer as it's a completely different solution. This follow the idea of creating private methods using closures (as linked to by OP in comment to my other answer - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Emulating_private_methods_with_closures).
This also draws on deceeze's comments on the original question, but casting the array to an object to more closely reflect the reference as being an object rather than an array...
function createGreeter($who) {
return (object)
[ "Hello" => function() use ($who) {
echo "Hello {$who}";
},
"Goodbye" => function() use ($who) {
echo "Goodbye {$who}";
}];
}
$op = createGreeter("me");
($op->Hello)();
($op->Goodbye)();
The ()'s around the methods are needed as it is a closure and not an actual method.
This gives...
Hello meGoodbye me
I am trying to do something like this:
//function name
$str = 'bla()';
//make function with string as name
function $str{
echo 'yey';
}
//Call the function by string name
bla();
You could use eval() to attempt this task. But I really do NOT suggest it:
// name of the function
$str = 'bla';
// php code you want to execute inside
$inside = '';
eval("
function $str() { $inside }
");
Or you could also use an anonymous function:
$name = function() {
// code
};
// execution
$name();
Als if you are just trying to call a dynamic function just use call_user_func() like this:
// name of the function
$str = 'bla';
// paramters to the function
$param = array();
call_user_func($str, $param);
But I think you are doing something wrong. This kind of "hacks" are sign of bad application architecture.
References
eval()
call_user_func()
Anonymous functions
I'll suggest you, not to use like this. But if still you want to do this,
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
Check here
And you are required to use PHP 5.3
Whenever a function completes, it RETURNS a value. If no value is set to be returned, 0 is returned.
If you would like to be able to do as you have asked, you could do the following:
function blah($string="Blah"){
return($string);
}
echo blah("Banana"); //echo's Banana
echo blah(); //echo's Blah
$str = blah("Apple"); //Sets $str to Apple
The following function is part of code written into the core of a plugin I am reverse engineering. The problem with it is that I need to do an str_replace on it and I cannot because it is already set to echo.
The function is.
function similar_posts($args = '') {
echo SimilarPosts::execute($args);
}
I call it in my pages using similar_posts(), but what I really need to do in my theme is call $related = similar_posts(), however that function is set to echo. How do I change that.
I tried this.
function get_similar_posts($args = '') {
SimilarPosts::execute($args);
}
But that did not produce any results.
function get_similar_posts($args = '') {
return (SimilarPosts::execute($args));
}
If you want to use the value SimilarPosts::execute ($args) returns, you'll need to use the keyword 'return' inside your get_similar_posts.
function get_similar_posts ($args = '') {
return SimilarPosts::execute($args);
}
If you are unable to change the definition of get_similar_posts there are ways to snatch the content printed by similar_posts even though it's "set to echo".
This can be accompished by using the Output Control Functions available in PHP.
function echo_hello_world () {
echo "hello world";
}
$printed_data = "";
ob_start ();
{
echo_hello_world ();
$printed_data = ob_get_contents ();
}
ob_end_clean ();
echo "echo_hello_world () printed '$printed_data'\n";
output
echo_hello_world () printed 'hello world'
Use return instead of echo.
So that you have:
return SimilarPosts::execute($args);
instead of:
echo SimilarPosts::execute($args);
Wrap the function inside another in which you use output buffering.
Done it..
function get_similar_posts($args = '') {
return SimilarPosts::execute($args);
}
and on the page get_similar_posts();
Should have thought of that.
return from the function:
function get_similar_posts($args = '') {
return SimilarPosts::execute($args);
}
I just simply want to create a function name with a string value.
Something like this:
$ns = 'test';
function $ns.'_this'(){}
test_this();
It of course throws an error.
I've tried with:
function {$ns}.'_this'
function {$ns.'_this'}
but no luck.
Any thoughts?
You can use create_function to create a function from provided string.
Example (php.net)
<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
?>
This is not possible. If all you want to do is, to prefix all functions with some common string, maybe you want to use namespaces?
namespace foo {
function bar() {}
function rab() {}
function abr() {}
}
// access from global namespace is as follows:
namespace {
foo\bar(); foo\rab(); foo\abr();
}
file with function (somefile.php)
function outputFunctionCode($function_name)
{?>
function <?php echo $function_name ?>()
{
//your code
}
<?php }
file with code which "declares" the function:
ob_start();
include("somefile.php");
outputFunctionCode("myDynamicFunction");
$contents = ob_get_contents();
ob_end_clean();
$file = fopen("somefile2.php", "w");
fwrite($file,$contents);
fclose($file);
include("somefile2.php");
It is ugly, but then again, it is an extremely bad idea to declare functions with dynamic names.
using "eval" is not a good practice, but that may serve the purpose similar to your requirements sometimes.
<?php
$ns = 'test';
$funcName = $ns.'_this';
eval("function $funcName(){ echo 1;}");
test_this();
?>
Is this what you are looking for?
<?php
function foo($a) { print 'foo called'.$a; }
$myfunctionNameStr = 'foo';
$myfunctionNameStr(2);
?>
Cause i don't think that you can dynamically construct a function declaration. You can decide at 'runtime' the value of the $myfunctionNameStr though.
I'm sure there's a very easy explanation for this. What is the difference between this:
function barber($type){
echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
... and this (and what are the benefits?):
function barber($type){
echo "You wanted a $type haircut, no problem\n";
}
barber('mushroom');
barber('shave');
Always use the actual function name when you know it.
call_user_func is for calling functions whose name you don't know ahead of time but it is much less efficient since the program has to lookup the function at runtime.
Although you can call variable function names this way:
function printIt($str) { print($str); }
$funcname = 'printIt';
$funcname('Hello world!');
there are cases where you don't know how many arguments you're passing. Consider the following:
function someFunc() {
$args = func_get_args();
// do something
}
call_user_func_array('someFunc',array('one','two','three'));
It's also handy for calling static and object methods, respectively:
call_user_func(array('someClass','someFunc'),$arg);
call_user_func(array($myObj,'someFunc'),$arg);
the call_user_func option is there so you can do things like:
$dynamicFunctionName = "barber";
call_user_func($dynamicFunctionName, 'mushroom');
where the dynamicFunctionName string could be more exciting and generated at run-time. You shouldn't use call_user_func unless you have to, because it is slower.
With PHP 7 you can use the nicer variable-function syntax everywhere. It works with static/instance functions, and it can take an array of parameters. More info at https://trowski.com/2015/06/20/php-callable-paradox
$ret = $callable(...$params);
I imagine it is useful for calling a function that you don't know the name of in advance...
Something like:
switch($value):
{
case 7:
$func = 'run';
break;
default:
$func = 'stop';
break;
}
call_user_func($func, 'stuff');
There are no benefits to call it like that, the word user mean it is for multiple user, it is useful to create modification without editing in core engine.
it used by wordpress to call user function in plugins
<?php
/* main.php */
require("core.php");
require("my_plugin.php");
the_content(); // "Hello I live in Tasikmalaya"
...
<?php
/* core.php */
$listFunc = array();
$content = "Hello I live in ###";
function add_filter($fName, $funct)
{
global $listFunc;
$listFunc[$fName] = $funct;
}
function apply_filter($funct, $content)
{
global $listFunc;
foreach ($listFunc as $key => $value)
{
if ($key == $funct and is_callable($listFunc[$key]))
{
$content = call_user_func($listFunc[$key], $content);
}
}
echo $content;
}
function the_content()
{
global $content;
$content = apply_filter('the_content', $content);
echo $content;
}
....
<?php
/* my_plugin.php */
function changeMyLocation($content){
return str_replace('###', 'Tasikmalaya', $content);
}
add_filter('the_content', 'changeMyLocation');
in your first example you're using function name which is a string. it might come from outside or be determined on the fly. that is, you don't know what function will need to be run at the moment of the code creation.
When using namespaces, call_user_func() is the only way to run a function you don't know the name of beforehand, for example:
$function = '\Utilities\SearchTools::getCurrency';
call_user_func($function,'USA');
If all your functions were in the same namespace, then it wouldn't be such an issue, as you could use something like this:
$function = 'getCurrency';
$function('USA');
Edit:
Following #Jannis saying that I'm wrong I did a little more testing, and wasn't having much luck:
<?php
namespace Foo {
class Bar {
public static function getBar() {
return 'Bar';
}
}
echo "<h1>Bar: ".\Foo\Bar::getBar()."</h1>";
// outputs 'Bar: Bar'
$function = '\Foo\Bar::getBar';
echo "<h1>Bar: ".$function()."</h1>";
// outputs 'Fatal error: Call to undefined function \Foo\Bar::getBar()'
$function = '\Foo\Bar\getBar';
echo "<h1>Bar: ".$function()."</h1>";
// outputs 'Fatal error: Call to undefined function \foo\Bar\getBar()'
}
You can see the output results here: https://3v4l.org/iBERh it seems the second method works for PHP 7 onwards, but not PHP 5.6.