简体   繁体   English

PHP create_function,函数没有分号?

[英]PHP create_function, function without semicolon?

basically, what i want to know is, for the second parameter in the create_function function, is there anyway to pass a string without a semicolon? 基本上,我想知道的是,对于create_function函数中的第二个参数,是否仍然要传递不带分号的字符串? or will it not work. 否则将无法正常工作。

example: 例:

taken from php.net
create_function('$a,$b', 'return "CRCs: " . crc32($a) . " , ".crc32(b);'),

notice that there is a semicolon in the string. 请注意,字符串中有分号。 is there any possible way someone can enter a function without a semicolon that will still run/evaluate? 有人可以输入没有分号但仍会运行/求值的功能,有什么可能的方式?

With create_function() you're creating an anonymous function. 使用create_function()可以创建一个匿名函数。 The second parameter is a string that is the code of the function (like any other function you'd write). 第二个参数是一个字符串,它是函数的代码(就像您要编写的任何其他函数一样)。 It doesn't have to end in a semicolon, for example: 它不必以分号结尾,例如:

$coolfunction = create_function('$thing', 'if ($thing > 0) {return "Yes"; } else { return "no!"; }');

echo $coolfunction(1) . ' and ' . $coolfunction(-1);

Ends in a '}' and prints out: Yes and no! 以'}'结尾并输出:是和否!

No it is not possible. 不,这是不可能的。 PHP is semicolon-sensitive, that you must use it to terminate every statements before right braces. PHP是分号敏感的,您必须使用它在右花括号之前终止所有语句。 I even tried regular function like this: 我什至尝试过这样的常规功能:

function f() {
  return 1
}

and it spitted out a syntax error, unlike in JavaScript. 与JavaScript不同,它吐出了语法错误。

You should always sanitize any user input before using it. 在使用任何用户输入之前,应始终对其进行清理。 I suggest that you look for the semicolon in the user input, if it is missing, append it. 我建议您在用户输入中查找分号,如果缺少分号,请附加分号。

If the user can enter anything here you still have a problem if he enters an invalid function name or just rubbish. 如果用户可以在此处输入任何内容,那么如果他输入的函数名称无效或只是垃圾,您仍然会遇到问题。

You can validate with preg_match() (although I'm not an expert on preg so I will let someone else help you out there). 您可以使用preg_match()进行验证(尽管我不是preg的专家,所以我会让别人在那里帮助您)。

First, why do you need that ? 首先,您为什么需要它? That's a really dirty way to create a function. 这是创建函数的一种非常肮脏的方式。 Hope because you want to make a interface where people can directly create a function (and this will be only for you or it'll be a big security issue). 希望如此,因为您希望创建一个界面,使人们可以直接创建功能(这将仅对您有用,否则将是一个很大的安全问题)。 I don't really get how you want to use that. 我真的不明白你想怎么使用它。

Anyway, for you question, you don't have to care if it's working or not. 无论如何,对于您的问题,您不必关心它是否有效。 I mean, just test if it's working, if not just put by yourself a semicolon. 我的意思是,请测试它是否有效,如果不是您自己写一个分号。 It's just a simply test on a string. 这只是对字符串的简单测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM