动态复制 PHP 函数
我正在开发一个需要复制和复制函数的项目即时执行,其中的变量也需要即时替换。
一个简单的例子如下:
function myfunction()
{
$abc = $_SESSION['abc'];
return $abc;
}
我希望能够调用 myfunction1() ,它实际上并不存在于代码中,但与上面的完全相同,只是它现在从我的自定义变量中获取值,所以它看起来像这:
function myfunction1()
{
$abc = $myCustomVariable;
return $abc;
}
有人帮忙吗?
I'm working on a project which requires a function to be copied & executed on the fly and variables in it needs to be replaced on the fly too.
A simple example will be like this:
function myfunction()
{
$abc = $_SESSION['abc'];
return $abc;
}
I want to be able to call myfunction1() which does NOT physically exist in the code but does exactly the samething as the one above except it now take values from my custom variable so it'll look like this:
function myfunction1()
{
$abc = $myCustomVariable;
return $abc;
}
Any one help pls?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您描述的函数的复杂程度越多,它听起来就越像是具有注入依赖项的对象的完美候选者。
例如,您可以(在这里仅描述基本接口):
然后您可以像这样使用它:
请查看 PHP 类和对象 以及其他相关主题。
The more you describe how convoluted your function is, the more it sounds like a perfect candidate for an object with injected dependencies.
For instance, you could have (just going to describe the basic interfaces here):
You can then use it like this:
Please take a look at PHP Classes and Objects and the other related topics.
这就是参数的用途,我想你想做这样的事情:
This is what parameters are for, I think your looking todo something like this:
直接答案是
eval
我这样做不推荐。您可以让您的函数接受一个参数,如下所示。
如果需要访问变量,但名称是由动态代码生成的,可以使用
$GLOBALS
。The direct answer is
eval
which I do not recommend.You could have your function accept a parameter, like this.
If you need to access a variable, but the name is generated by dynamic code, you can use
$GLOBALS
.