我从未在PHP中看到过这种情况。大多数PHP示例和教程在声明之后使用函数调用的格式,但在这里我第一次尝试它。我认为PHP使用解释器并逐行读取代码。当它在第3行之前没有检测到任何函数声明时,它不应该在第3行产生错误吗?
<?php
$m=new m;
echo $m->abd(17,18);
class m
{
function abd($a,$b)
{
return($a+$b);
}
}
?>
但输出
35
这可能吗? 作为参考,这是您可以尝试此代码的Sandbox Link
答案 0 :(得分:1)
在引用函数之前不需要定义函数,除非有条件地定义函数,如下面两个示例所示。
但是,在使用它们之前定义函数似乎是一种好习惯
这两个例子是
<?php
$makefoo = true;
/* We can't call foo() from here
since it doesn't exist yet,
but we can call bar() */
bar();
if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}
/* Now we can safely call foo()
since $makefoo evaluated to true */
if ($makefoo) foo();
function bar()
{
echo "I exist immediately upon program start.\n";
}
?>
和
<?php
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}
/* We can't call bar() yet
since it doesn't exist. */
foo();
/* Now we can call bar(),
foo()'s processing has
made it accessible. */
bar();
?>
有关详细信息,此答案来自another SO answer