gpt4 book ai didi

php - 为什么定义一个函数算作多个语句?

转载 作者:行者123 更新时间:2023-12-02 02:41:57 25 4
gpt4 key购买 nike

我在 PHP 中看到了一个奇怪的行为。看这个例子:

<?php
if (true)
function my_function(){
echo "here";
}

my_function();
?>

运行这个会报错:

Parse error: syntax error, unexpected 'my_function' (T_STRING), expecting '(' on line 4

我发现这个错误的修复方法是添加括号:

<?php
if (true) {
function my_function(){
echo "here";
}
}
my_function();
?>

此代码将正常运行。

你能解释一下吗?为什么定义一个函数算作多个语句?

最佳答案

函数定义不是语句。

你问:

Why defining a function count as more than one statement?

事实并非如此。定义函数不是语句。

来自 PHP Manual :

A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well.

if 语句后必须跟另一个语句!让我们简化您的问题,看看上面定义的此类语句的一些示例:

if(1)
{} // A statement-group is a statement by itself as well.
if(1)
; // an empty statement
if(1)
$a=1; // an assignment
if(1)
print(1); // a function call
if(1)
while(0){} // a loop
if(1)
if(0); // a conditional statement

根据官方 PHP 定义,函数或类的定义不是语句。非语句不能用在需要语句的上下文中。

什么时候函数定义是语句?

PHP 5.3 引入了匿名函数的概念(Lambda 函数和闭包)。匿名函数定义是一个语句。

匿名函数的语法与普通函数定义几乎相同,但您不需要提供名称。换句话说,关键字 function 必须跟在 () 之后,它们之间只允许有空格。它还必须以分号结尾。

// This is valid:
if(1)
function (){};
//This is invalid:
if(1)
function a(){}
// ^
// syntax error, unexpected 'a' (T_STRING), expecting '('

这就是错误消息告诉您函数名称不正确的原因。 PHP 需要一个语句,当它遇到 function 关键字时,它希望您正在定义一个匿名函数。匿名函数没有名称,因此名称部分是意外的。

关于php - 为什么定义一个函数算作多个语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58936926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com