PHP变量函数和语言结构(PHP Variable Functions and language constructs)

编程入门 行业动态 更新时间:2024-10-26 10:31:49
PHP变量函数和语言结构(PHP Variable Functions and language constructs)

我试图理解为什么变量函数的PHP文档说明:

变量函数不适用于语言结构,如echo,print,unset(),isset(),empty(),include,require等。 利用包装器函数将这些结构中的任何一个用作可变函数。

我尝试了其中一些并且它们工作得很好:

function animal() { return 'Monkey'; } $animal = 'animal'; echo $animal();

返回Monkey - 正如人们所期望的那样。

与print构造相同的结果 - 然后我尝试了unset() ,它也可以正常工作:

function getIndex() { return 0; } $index = 'getIndex'; $array = array( 'Monkey', 'Gorilla' ); unset($array[$index()]); print_r($array);

这将返回Array ( [1] => Gorilla ) 。

这里有什么我想念的吗? 只是添加 - 我使用的是PHP 5.5.14。

I'm trying to understand why PHP documentation for variable functions states that:

Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

I tried some of these and they work just fine:

function animal() { return 'Monkey'; } $animal = 'animal'; echo $animal();

returns Monkey - just as one would expect.

Same result with print construct - then I tried unset() and it also works absolutely fine:

function getIndex() { return 0; } $index = 'getIndex'; $array = array( 'Monkey', 'Gorilla' ); unset($array[$index()]); print_r($array);

this returns Array ( [1] => Gorilla ).

Is there something I'm missing here? Just to add - I'm using PHP 5.5.14.

最满意答案

您实际上并没有将任何语言结构用作变量函数:

但试试吧

$function = 'echo'; $function('Hello World');

它完全不像文档中所描述的那样不起作用

如手册中所述,使用echo周围的包装函数,然后可以将该函数用作变量函数

function myecho($value) { echo $value; } $function = 'myecho'; $function('Hello World');

You're not actually using any language constructs as a variable function:

But try

$function = 'echo'; $function('Hello World');

and it won't work, exactly as described in the docs

Use a wrapper function around echo as described in the manual, and then you can use that function as a variable function

function myecho($value) { echo $value; } $function = 'myecho'; $function('Hello World');

更多推荐

本文发布于:2023-08-01 10:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1357721.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   函数   语言   结构   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!