php如何执行分配给变量的函数?

时间:2009-05-22 13:35:31

标签: php

好吧,我真的不知道怎么说这个问题,但让我解释一下。

假设我有一个变量:

$file = dirname(__FILE__);

如果我将$file分配给另一个变量会怎样?

$anotherVariable = $file;

每次分配时都会执行dirname函数吗?

感谢您的帮助。

4 个答案:

答案 0 :(得分:12)

没有。 PHP是必不可少的,因此赋值表达式的右侧是评估,结果存储在“左侧”(在简单且几乎无处不在的情况下,左侧指定的变量) )。

$a = $b;  // Find the value of $b, and copy it into the value of $a
$a = 5 + 2; // Evaulate 5 + 2 to get 7, and store this in $a
$a = funcName(); // Evaluate funcName, which is equivalent to executing the code and obtaining the return value. Copy this value into $a

当你通过引用分配($ a =& $ b)时,这会变得有点复杂,但我们暂时不用担心。

答案 1 :(得分:2)

PHP没有这样的闭包。

  

目录名(文件

此函数返回一个字符串。

  

$ anotherVariable = $ file;

给$ anotherVariable提供相同的字符串值。

所以我相信你的问题的答案是“不”,每次都没有执行。

答案 2 :(得分:2)

回答主要问题:

$a = function(){ echo "Hello!"; };
$a();

对小问题的回答:

$file = dirname(__FILE__); 
//means: 
//"Evaluate/Execute function dirname() and store its return value in variable $file"
  

如果我将$ file分配给另一个变量会怎样?

如果我们谈论的是常规作业($anotherVariable = $file;),那么将值$file复制到$anotherVariable两者都是自变量

  

每次分配时都会执行dirname函数吗?

不,不。因为只能使用()执行。否() =无执行。

答案 3 :(得分:1)

在任何情况下都没有。

PHP的函数不是指向类函数实例的标识符,你可以在Java,ActionScript,JavaScript等中看到......这就是为什么你不能存储一个函数本身的链接到变量的原因。这就是为什么你调用函数时它与你包含()脚本执行的共同点。当然存在差异,但在这个问题的上下文中包括include()和调用函数几乎完全相同。

不要与此案混淆

function myFunc() {return 'hello world';}
$func = 'myFunc';
$a = $func();
echo $a; // hello world

阅读本案例here此行为对PHP特殊。不确定其他语言 - 也许somwhere有smth。与此类似,但我从未见过它。