可变变量、函数和类
我最近在 PHP 中发现了可变变量,不用说,它的用处是巨大的:
$name = "ABC";
$$name = "DEF";
echo ${"ABC"}; //Gives: DEF
这让我思考,这让我们想到了我的问题:
既然我们可以有变量的名称,我们不能也有这样的函数吗?的变量? 不是函数名称中的“函数”,而是(或多或少)如下:
$func = 'function test() { echo "Success!"; }';
$func(); //If this would work, it would give: Success!
或者,更好的是,变量类:
$class = 'class { function test() { echo "Success!"; } }';
$instance = new $class;
$instance->test(); //In a (not-so) perfect world this would give: Success!
这可能吗?
I just recently discovered variable variables in PHP, needless to say, it´s usefulness is immense:
$name = "ABC";
$name = "DEF";
echo ${"ABC"}; //Gives: DEF
That got me thinking, which brings us to my question:
Since we can have names that´s variable, can´t we also have functions that´s variable?
Not 'functions' as in the names of functions, but (more or less) as in:
$func = 'function test() { echo "Success!"; }';
$func(); //If this would work, it would give: Success!
Or, even better, variables classes:
$class = 'class { function test() { echo "Success!"; } }';
$instance = new $class;
$instance->test(); //In a (not-so) perfect world this would give: Success!
Any of this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你大错特错了。
可变变量绝对没有什么了不起的。您最好发现数组
PHP 也具有可变函数名称,并且它更有用一点,但它仍然使阅读您的代码成为一种折磨。因此,最好也避免它们。
请记住最著名的只写语言的命运。 PHP一口气吃掉了,只是因为PHP的可读性。不要尝试用 PHP 来制作 Perl。编写代码是一种休闲,但寻找代码中的错误是一项真正的工作。不要让你的工作变得更困难。
不要编写晦涩难懂的代码。
编写直接、干净的代码。
你会给自己和其他碰巧使用它的人带来巨大的帮助。
You cannot be more wrong.
There is absolutely nothing great about variable variables. You'd better discovered arrays
PHP has variable function names as well and it's a bit more usable but still it makes reading your code a torture. So, better to avoid them as well.
Remember the fate of most-known write-only language. PHP ate it in one gulp, only because of PHP's readability. Do not try to make Perl out of PHP. Writing code is leisure but hunting down errors in it - is a REAL job. Don't make your job harder.
Do not write obscure and puzzled code.
Write straight and clean code.
You'd make a huge favor to yourself and other people who happen to work with it.
不知道你的第三个例子,但你的第二个例子应该几乎可以工作(假设你使用的是 php 5.3 或更高版本;))。只需留下引号和函数名称:
搜索“匿名函数”,或者要了解更多相关信息,请查看 文档。
don't know about your third example, but your second one should almost work (assuming you're using php 5.3 or higher ;) ). just leave yout the quotes and the functions name:
search for "anonymous function" or, to read more about this, just take a look at the documentation.
唯一有效的方法是使用
eval
。您也可以使用变量来调用函数。
请记住 - 您正在进入 PHP 的危险区域,因为这通常只会混淆您的代码,以便任何未来的开发人员必须维护您的代码(包括几个月后的您自己)。
The only way this would work is using
eval
.You can use variables to call functions as well.
Keep in mind - you're entering a dangerous area of PHP as this usually only obfuscates your code for any future developers having to maintain your code (including yourself in a few months).