How do I convert another create_function. The one below
return create_function('$f,$e=null', "return ($parsed_tpl);");
to
$e=null;
return function($f,$e) { return ($parsed_tpl); };
or
return function($f,$e=null;) { return ($parsed_tpl); };
But neither of them are working.
I have tried everything above.
The key part to notice on the original code is this:
"return ($parsed_tpl);"
Note the double-quotes, meaning the variable will be expanded in the string before passing it to create_function. Then the expanded form will form the body of the function.
In other words, the actual code of the created function will be completely different every time - it won't just return the string, it will execute it as PHP code.
To achieve the same effect in current PHP, you need to use the eval function:
return eval("return ($parsed_tpl);");
You also have two mistakes in your attempt:
$e=null isn't an assignment, it's a default value for the parameter; it doesn't need a semicolon
You have to "capture" the $parsed_tpl variable with the use keyword to use it inside the function
The format is this:
$my_anonymous_function =
function($some_param, $next_param='default value', $another='another default')
use ($something_captured, $something_else) {
/* body of function using those 5 variables*/
};
Related
I am confused about return statement , why we need to use return in end of function , for example
function test($a){blah;
blahh ;
blahhh;
blahhhhh;
return;}
What the use of return here? Function automatically terminates when all the statements executed , I think there is no use of return here , but this picture from http://www.w3resource.com/php/statement/return.php make me confused
So
Can someone please explain the use of return (when we not returning any value).
It depends on what you're trying to achieve.
If you write echo in several places, your code will get confusing. In general, a function that returns a value is also more versatile, since the caller can decide whether to further manipulate that value or immediately print it.
I'd recommend to stick to the convention and use return for a function.
You should check GuardClause.
Example:
function test() {
return 10;
}
$a = test(); // $a stores the value 10
echo $a; // Prints 10
echo $a + 5; // We may want to manipulate the value returned by the function. So, it prints 15.
For further reference, check What is the difference between PHP echo and PHP return in plain English?
In that context: You don't.
return breaks out of the function, but since it is the last statement in that function, you would break out of it anyway without the statement.
return passes its argument back to the caller, but since it doesn't have an argument, there is nothing to pass.
So it does nothing.
Don't assume that every piece of code you stumble across has a purpuse. It might be left over from an earlier version of the code where something else (which gave it meaning) has been removed. It might be written by someone cargo culting. It might be placeholder for future development.
"return" is important when you plan to call this function from other codes, it helps you to:
Know if the function works correctly, or not.
Obtain values from a function.
Make sure other codes are not executed after return.
It might be useless when the code is simple as your sample, let's make it more complex.
function test($a){
if(file_exists($a)){
if(is_file($a)){
return $a." IS A FILE\n";
} else if(is_dir($a)) {
return $a." IS A DIR\n";
} else {
return $a." EXISTS, BUT I DONT KNOW WHAT IT IS\n"
}
} else {
return $a." NOT EXISTS\n";
}
return 0;
}
$filecheck = test("/abc/def.txt");
if($filecheck){
echo $filecheck;
} else {
echo "unknown error";
}
Above shows how to return a value, and do some basic handling.
It is always good to implement return in your functions so you can even specify error code for your functions for reference.
Based on your example, I'll modify slightly like below:
function test($a){
blah;
blahh;
blahhh;
blahhhhh;
return 1;
}
So I know the code is running to last line.
Otherwise the function just finishes silently.
It's useful if you want a function to return a value.
i.e.
Function FavouritePie($who) {
switch($who) {
case 'John':
return 'apple';
case 'Peter':
return 'Rhubarb';
}
}
So, considering the following:
$WhatPie = FavouritePie('John');
echo $WhatPie;
would give
apple
In a really simple form, it's useful if you want a function to return something, i.e. process it and pass something back. Without a return, you'd just be performing a function with a dead end.
Some further reading:
http://php.net/manual/en/function.return.php
http://php.net/manual/en/functions.returning-values.php
To add some further context specific to the answer, if the question boils down to "Do I need to add a return for the sake of it, at the end of a function, then the answer is no. But that doesn't mean the correct answer is always to leave out your return.
it depends what you want to do with $a.
If you echo $a within the function, that function will spit out $a as soon as it is called. If you return $a, assuming you set the calling of test to a variable (i.e. $something = $test('foo')), then you can use it later on.
I have this code:
return t("Use tokens like: eg. [youtube_video:id]");
Because of the brackets used in my string PHP treat this [youtube_video:id] as an array key and returns notice like: Notice: Use of undefined constant _miscellaneous_filter_tips - assumed '_miscellaneous_filter_tips' w miscellaneous_filter_info_alter()
How can I resolve it?
All the code after a request:
function _miscellaneous_filter_tips() {
return t('Use tokens like: eg. [yamandi:youtube_video:id]');
}
function miscellaneous_filter_info_alter(&$info) {
$info['filter_tokens']['tips callback'] = _miscellaneous_filter_tips;
}
since I don't have the precursor code I can't actually see what the function t() does, however if is seems to think you are calling a variable try using
return t('Use tokens like: eg. [youtube_video:id]');
or if you still want to use variables
return t("Use tokens like: eg. " . '[youtube_video:id]');
Just change the double quote into a single quote:
return t('Use tokens like: eg. [youtube_video:id]');
EDIT
After looking to the updated code, this might be a completely different issue, I think you might wanna try this way of storing function hooks:
function _miscellaneous_filter_tips() {
return t('Use tokens like: eg. [yamandi:youtube_video:id]');
}
function miscellaneous_filter_info_alter(&$info) {
$info['filter_tokens']['tips callback'] = '_miscellaneous_filter_tips';
}
And then when you want to call that function, you can simply use:
$info['filter_tokens']['tips callback']();
I'm writing my own debug functions and I need some help to fix the code below.
I'm trying to print a variable and its name, the file where the variable and the function was declared and the line of the function call. The first part I did, the variable, the variable name, the file and the line is printed correctly.
At the code, a($variable) works good.
The problem is I'd like this function accepts a string too, out of a variable. But PHP returns with a fatal error (PHP Fatal error: Only variables can be passed by reference in ...). At the code, a('text out').
So, how can I fix this code to accept a variable or a string correctly?
code (edited):
function a(&$var){
$backtrace = debug_backtrace();
$call = array_shift($backtrace);
$line = $call['line'];
$file = $call['file'];
echo name($var)."<br>".$var."<br>".$line."<br>".$file;
}
$variable='text in';
a($variable);
a('text out');
I need pass the variable by reference to use this function below (the function get the variable name correctly, works with arrays too):
function name(&$var, $scope=false, $prefix='unique', $suffix='value'){
if($scope) $vals = $scope;
else $vals = $GLOBALS;
$old = $var;
$var = $new = $prefix.rand().$suffix;
$vname = FALSE;
foreach($vals as $key => $val) {
if($val === $new) $vname = $key;
}
$var = $old;
return $vname;
}
The way your code is currently implementing pass by reference is perfect by design, but also by design cannot be changed to have two a() methods - one accepting a variable by reference and the other as a string-literal.
If the desire to pass a string literal instead of assigning it to a variable first is really needed, I would suggest creating a second convenience method named a_str() that actually accepts a string-literal instead of a variable by reference. This method's sole-purpose would be to relay the variable(s) to the original a() method - thereby declaring a variable to pass by reference.
function a_str($var) {
a($var);
}
The only thing to remember is, use a($variable); when passing by reference and a_str('some text'); when not.
Here is the same convenience-method for your name() function:
function name_str($var, $scope=false, $prefix='unique', $suffix='value'){
return name($var, $scope, $prefix, $suffix);
}
The only way to do what you are asking without writing an additional function like #newfurniturey suggests is plain and simply opening and parsing the file where your function was called as text (e.g. with fopen), using the data from debug_backtrace. This will be expensive in terms of performance, but it might be ok if used only for debugging purposes; and using this method you will no longer need a reference in your function, which means you can freely accept a literal as the parameter.
my question is really basic but I really can't figure out how to do it.
Basically I have a javascript function into an HTML document that changes my uploading parameters as follows:
function change(){
upload.url ( 'upload.php?country=COUNTRYISOSTRING' );
}
Now, basing on a selection made by the user through PHP or HTML function (such as IP country detection or simple HTML dropdown menu), I would like to change the COUNTRYISOSTRING passing it to the function instead of writing different functions for each choice, so it would become
function change($countrycode) {
upload.url ( 'upload.php?country=$countrycode' );
}
But it's not working...What am I doing wrong?
I don't really understand what you are exactly trying to do but something like this should definitively work:
function change(country){
upload.url ( 'upload.php?country=' + country);
}
Edit: misunderstood the question. In JavaScript variables don't need the dollar sign, and are not evaluated inside strings; you need to concatenate the parameter like this:
function change(countrycode) {
upload.url ( 'upload.php?country=' + countrycode );
}
Better to pass your php variable as a parameter to the function call:
function change(countryCode) {
upload.url('upload.php?country=' + countrycode);
}
And call this function like:
change('<?php echo $countryCode; ?>')
Ok, I'm looking into using create_function for what I need to do, and I don't see a way to define default parameter values with it. Is this possible? If so, what would be the best approach for inputting the params into the create_function function in php? Perhaps using addslashes?
Well, for example, I have a function like so:
function testing($param1 = 'blah', $param2 = array())
{
if($param1 == 'blah')
return $param1;
else
{
$notblah = '';
if (count($param2) >= 1)
{
foreach($param2 as $param)
$notblah .= $param;
return $notblah;
}
else
return 'empty';
}
}
Ok, so how would I use create_function to do the same thing, adding the parameters and their default values?
The thing is, the parameters are coming from a TEXT file, as well as the function itself.
So, wondering on the best approach for this using create_function and how exactly the string should be parsed.
Thanks :)
Considering a function created with create_function this way :
$func = create_function('$who', 'echo "Hello, $who!";');
You can call it like this :
$func('World');
And you'll get :
Hello, World!
Now, having a default value for a parameter, the code could look like this :
$func = create_function('$who="World"', 'echo "Hello, $who!";');
Note : I only added the default value for the parameter, in the first argument passed to create_function.
And, then, calling the new function :
$func();
I still get :
Hello, World!
i.e. the default value for the parameter has been used.
So, default values for parameters work with create_function just like they do for other functions : you just have to put the default value in the list of parameters.
After that, on how to create the string containing the parameters and their values... A couple of string concatenations, I suppose, without forgetting to escape what should be escaped.
Do you want to create an anonymous function? The create_function is used to create the anonymous functions. Otherwise you need to create function normally like:
function name($parms)
{
// your code here
}
If you want to use the create_function, here is the prototype:
$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
I'm having the same problem, trying to pass an array to a created callback function... I think I'll create a temporary variable... It's ugly but I have better to do then torture myself with slashes, my code is already cryptic enough the way it is now.
So, to illustrate:
global $tmp_someArray;
$tmp_someArray = $someArray;
$myCallback = create_function(
'$arg1',
'
global $tmp_someArray;
// do stuff with $tmp_someArray and $arg1....
return($something);
'
);