How to put PHP string in a function name?
for ($i=1;$i<10;$i++) {
function my_function_$i() {
//Parse error: syntax error, unexpected T_VARIABLE, expecting '('
include($i.'.php');
}
}
UPDATE:
OK. closed this question, I shall study for more.
there is something utterly wrong with your architecture if you come to a question like this.
it seems you do not understand what functions are for.
there should be no functions like my_function_$i() but one function my_function($i)
There should be no enumerated includes as well. What are these php files for?
Check this out - maybe what you're looking for
http://php.net/manual/en/function.create-function.php
from that page:
<?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
?>
Firstly, this is a horrible thing to do. Consider using closures, or create_function(), or passing $i as an argument.
Secondly - the only way I can think of to do this (but for Christ's sake, don't) is with eval():
for ($i = 1; $i < 10; $i++) {
eval("function my_function_$i() {
include('$i.php');
}");
}
Maybe you can use eval for do like this:
for ($i=1;$i<10;$i++) {
eval('function myfunc_'.$i.'(){echo '.$i.';}');
}
myfunc_5();
//Output
//5
Related
So I am currently in the middle of making a forums software. Something that I wanted for that forums software was a custom template engine. For the most part I have created the template engine, but I am having a small issue with the regex that I use for my IF, ELSEIF, and FOREACH statements.
The issue that I am having is that when I put a chunk of html code in to my regex, nothing will work. Here is an example: https://regex101.com/r/jlawz3/1.
Here is the PHP code that checks for the regex.
$isMatchedAgain = preg_match_all('/{IF:(.*?)}[\s]*?(.*?)[\s]*?{ELSE}[\s]*?(.*?)[\s]*?{ENDIF}/', $this->template, $elseifmatches);
for ($i = 0; $i < count($elseifmatches[0]); $i++) {
$condition = $elseifmatches[1][$i];
$trueval = $elseifmatches[2][$i];
$falseval = (isset($elseifmatches[3][$i])) ? $elseifmatches[3][$i] : false;
$res = eval('return ('.$condition.');');
if ($res===true) {
$this->template = str_replace($elseifmatches[0][$i],$trueval,$this->template);
} else {
$this->template = str_replace($elseifmatches[0][$i],$falseval,$this->template);
}
}
You can do it like this:
function render($content) {
$match = preg_match_all('/{IF:\((.*?)\)}(.*?){ELSE}(.*?)({ENDIF})/s', $content, $matches, PREG_OFFSET_CAPTURE);
if (!$match) {
return $content;
}
$beforeIf = substr($content, 0, $matches[0][0][1]);
$afterIf = substr($content, $matches[4][0][1] + strlen('{ENDIF}'));
$evalCondition = eval('return (' . $matches[1][0][0] . ');');
if ($evalCondition) {
$ifResult = $matches[2][0][0];
} else {
$ifResult = $matches[3][0][0];
}
return
$beforeIf .
$ifResult .
render($afterIf);
}
Working example.
This is a first step. This wont work for example if you have an if within an if.
Talking about mentioned security risk. Since we are using eval (nickname EVIL - for a reason). You should never ever ever process user-input through eval - or use eval at all - there is always a better solution.
For me it looks like you want to give users the ability to write "code" in their posts. If this is the case you can have a look at something like bbcode.
Whatever you do be sure to provide the desired functionality. Taking your example:
!isset($_SESSION['loggedin'])
You could do something like this:
{IS_LOGGED_IN}
Output whatever you want :)
{/IS_LOGGED_IN}
Your renderer would look specificly for this tag and act accordingly.
So after a bit of research, I have figured out that the issue I was facing could be solved by adding /ims to the end of my regex statement. So now my regex statement looks like:
/{IF:(.*?)}[\s]*?(.*?)[\s]*?{ELSE}[\s]*?(.*?)[\s]*?{ENDIF}/ims
What is the best way to go about defining a php function and the call to that function, in a string, and then executing that code i.e., eval? I'm trying to get the length of an encoded uri out of a function defined and called in a string.
$json_arr['my_function'] = "function hashfun1($enc_uri) { return strlen($enc_uri); } hashfun1($enc_uri);";
$hash_func = $json_arr['my_function'];
$hash_val = eval($hash_func);
print_r($hash_val); // should be length of encoded uri but displays "Parse error: syntax error, unexpected '%', expecting '&' or T_VARIABLE"
exit;
Thanks.
I guess you want:
$json_arr['my_function'] = "function hashfun1($enc_uri) { return strlen($enc_uri); } hashfun1('" . $enc_uri . '");";
You missed to populate $enc_uri.
Don't do this in production code, although it works. eval() is evil. You have been warned.
you need to escape "$" in double-quoted string. And check number of returns (second for eval):
$json_arr['my_function'] = "function hashfun1(\$enc_uri) { return strlen(\$enc_uri); } return hashfun1(\$enc_uri);";
I guess I need to use call_user_func(); This worked for me: $json_arr['my_function'] = function($enc_uri) { return strlen($enc_uri); };
$hash_val = call_user_func($json_arr['my_function'], $enc_uri);
print_r($hash_val);
exit;
Thanks for the help guys.
I'm just learning PHP, and I'm sure I'm not the first person to try something like this, but maybe because I didn't know what to call it, I couldn't find any other examples or questions on here or from a search on google.
I wanted to create a function which takes two parameters and uses them to create all the short style variables I'll be using later in my script.
My problem is where normally the syntax to create a short variable is something like:
$var = $_METHOD['var'];
but I'm trying to do this using variables and don't know how to get the syntax right. Here's my code:
<?php
session_start();
function shortnames($some_vars, $type) {
for ($i = 0; $i<(count($some_vars)); $i++) {
$$some_vars[$i] = $_$type['$some_vars[$i]'];
echo $$some_vars[$i].' = '.$some_vars[$i].'<br />';
}
}
$post_vars = array(lastname,firstname,payment);
$session_vars = array(sessiontxt,province,city,venue,regfee);
shortnames($session_vars,session);
shortnames($post_vars,post);
?>
Thanks for helping a beginner!!
I want to create and execute a closure within a string in PHP and it's not liking the way that I do it.
This code doesn't work...
echo ( 'Hello, ' . (function($s) { return $s; })('World!') );
Yet, this is completely valid and works as intended...
$f = (function($s) { return $s; });
echo ( 'Hello, ' . $f('World!') );
Why won't the first one work and is there a way to do it in one line (not because I think it's efficient, because I'm sure it's not)?
You may want to take a look at Self Executing functions in PHP5.3?.
Essentially, no self-invoking with "(...)()" until (maybe) sometime in 5.4.
https://wiki.php.net/rfc/fcallfcall
I believe that's only possible in PHP 5.4: http://php.net/manual/en/migration54.new-features.php
Please could someone experienced in PHP help out with the following. Somewhere in my code, I have a call to a public static method inside a non-instantiated class:
$result = myClassName::myFunctionName();
However, I would like to have many such classes and determine the correct class name on the fly according to the user's language. In other words, I have:
$language = 'EN';
... and I need to do something like:
$result = myClassName_EN::myFunctionName();
I know I could pass the language as a parameter to the function and deal with it inside just one common class but for various reasons, I would prefer a different solution.
Does this make any sense, anyone? Thanks.
Use the call_user_func function:
http://php.net/manual/en/function.call-user-func.php
Example:
call_user_func('myClassName_' . $language . '::myFunctionName');
I think you could do:
$classname = 'myClassName_' . $language;
$result = $classname::myFunctionName();
This is called Variable Functions
I would encapsulate the creation of the class you need in a factory.
This way you will have a single entry point when you need to change your base name or the rules for mapping the language to the right class.
class YourClassFactory {
private $_language;
private $_basename = 'yourclass';
public YourClassFactory($language) {
$this->_language = $language;
}
public function getYourClass() {
return $this->_basename . '_' . $this->_language;
}
}
and then, when you have to use it:
$yourClass = $yourClassFactoryInstance->getYourClass();
$yourClass::myFunctionName();
As temuri said, parse error is produced, when trying '$className::functionName' :
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM ...
In my case (static method with 2 arguments), best solutions is to use call_user_func_array with 2 arrays (as suggested by nikc.org):
$result = call_user_func_array(array($className, $methodName), array($ard1, $arg2));
BR
although i think the way you deal is a very bad idea, i think i may have a solution
$className = 'myClassName_'.$language;
$result = $className::myFunctionName();
i think this is what you want
You can easily do next:
<?php
class B {
public static $t = 5;
public static function t($h) {
return "Works!" . $h;
}
}
$g = 't';
$class = 'B';
echo $class::$g('yes'); //Works! Yes
And it will works fine, tested on PHP 5.2 >=
As far as i could understand your question, you need to get the class name which can be done using get_class function. On the other hand, the Reflection class can help you here which is great when it comes to methods, arguments, etc in OOP way.
Solutions like:
$yourClass::myFunctionName();
will not work. PHP will produce parse error.
Unfortunately, the only way is to use very slow call_user_func().
I know it's an old thread, but as of PHP 5.3.0 you should be using forward_static_call
$result = forward_static_call(array('myClassName_EN', 'myFunctionName'));
Using your $language variable, it might look like:
$result = forward_static_call(array('myClassName_' . $language, 'myFunctionName'));