简体   繁体   English

PHP可以执行类似p($ i)的操作,并显示“ $ i is 5”吗— C和Ruby可以……(即自动打印出“ $ i”)

[英]can PHP do something like p($i) and it prints “$i is 5” — C and Ruby can… (that is, to print out “$i” automatically)

I was wondering if PHP can do this as there seems to be no good solution to it yet: 我想知道PHP是否可以做到这一点,因为似乎还没有很好的解决方案:

p($i)

and it will print 它会打印

$i is 5

and

p(1 + 2)

will print 将打印

1 + 2 is 3

and

p($i * 2)  =>  $i * 2 is 10  
p(3 * factorial(3))  =>  3 * factorial(3) is 18

C and Ruby both can do it... in C, it can be done by stringification, and in Ruby, there is a solution using p{'i'} or p{'1 + 2'} (by passing the block with the binding over, to do an eval)... I wonder in PHP, is it possible too? C和Ruby都可以做到...在C语言中,可以通过字符串化来完成,而在Ruby中,有一个使用p{'i'}p{'1 + 2'}的解决方案(通过使用绑定结束,进行评估)...我想知道在PHP中,是否也可能?

I think it could be done by taking a backtrace then loading and tokenizing the file that calls p() . 我认为可以通过回溯然后加载并标记调用p()的文件来完成。 I wouldn't call it a "good" solution though. 我不会称其为“好”解决方案。

Of course you could stringify it yourself... 当然你可以自己把它串起来...

p('$i');

function p($str) 
{
    echo $str, " = ", eval("return ($str);");
}

If you mess with the string to make it into a return statement, you can use eval ... 如果将字符串弄乱以使其成为return语句,则可以使用eval ...

function p($expr)
{
   $php="return {$expr};";
   echo "$expr is ".eval($php)."\n";
}


p("1+2");

Works for simple expressions, but if you tried to reference a variable in your $expr, then it wont find it inside the scope of function p() - a little hack like the following can help: 适用于简单表达式,但是如果您尝试在$ expr中引用变量,那么它将无法在函数p()的范围内找到它-像下面这样的hack可以帮助您:

function p($expr)
{
   $php="return {$expr};";
   $php=preg_replace('/\\$(\w+)/', '$GLOBALS[\'$1\']', $php);


   echo "$expr is ".eval($php)."\n";
}

$x=5;
p('$x+4');

Here we've search for variable references in the code and turned them into $GLOBALS array references. 在这里,我们在代码中搜索变量引用,并将它们转换为$ GLOBALS数组引用。 The expression $x+4 is turned into return $GLOBALS['x']+4; 表达式$x+4变为return $GLOBALS['x']+4;

Not sure I'd ever want to see this in production code though :) 虽然不确定我是否想在生产代码中看到它:)

好吧,如果您传入一个字符串,则可以使用eval进行计算。

Short answer: no 简短答案:否

The problem with eval() based solutions is scope. 基于eval()的解决方案的问题在于范围。 The following won't work: 以下内容不起作用:

function p($expr)
{
   $php="return {$expr};";
   echo "$expr is ".eval($php)."\n";
}

$i = 10;

p('$i + 1');

because $i won't be in scope when eval() is called. 因为在调用eval()时$ i不在范围内。

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

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