当一个异常发生时,我试图在我的错误日志中显示数组的内容。
我不明白为什么print_r
不能按以下代码的预期工作:
throw new ExcepcionApi(BAD_URL, ("Bad URL: {print_r($peticion,TRUE)}"));
在日志文件中:
PHP Fatal error: Uncaught ExcepcionApi: Bad URL: {print_r(Array,TRUE)} in / ...
这很好:
$errorMsg=print_r($peticion,TRUE);
throw new ExcepcionApi(BAD_URL, ("Bad URL: $errorMsg"));
在日志文件中:
PHP Fatal error: Uncaught ExcepcionApi: Bad URL: Array
(
[0] => fakeURL
[1] => fakeParams
)
为什么print_r
在第一种情况下不起作用?
答案 0 :(得分:1)
引用PHP Manual:
注意: 函数,方法调用,静态类变量和类常量 自PHP 5起,在{$}内部工作。但是,访问的值将是 在字符串的作用域中解释为变量的名称 被定义为。使用单个大括号({})无法访问 函数或方法的返回值或类的值 常量或静态类变量。
这意味着您可以在表达式内部使用函数和方法调用,但只能获取变量名称,例如:
$myvar = "Hello";
function whichvar() {
return "myvar"; // Returns a variable name
}
// gets variable by a name from the function
print "Result is: {${whichvar()}}"; // Result is: Hello
或获取数组索引等。
$myarr = array(
'notthis' => 'Bad',
'andnotthistoo' => 'Too Bad',
'this' => 'Good'
);
function whichidx() {
return 'this';
}
print "I like {$myarr[whichidx()]}"; // I like Good
但是无法获得函数本身的结果。
实际上我不明白为什么您首先需要它。您始终可以使用.
运算符来使用简单的字符串连接:
throw new ExcepcionApi(BAD_URL, ("Bad URL: " . print_r($peticion,TRUE)));