在PHP函数中调用命名参数

huangapple go评论63阅读模式
英文:

Calling Named Argument in PHP Function

问题

我是一个Flutter开发者,我曾经使用以下函数:

String getVar({required String $a, bool $b = true}) {
  if ($b) {
    return $a;
  } else {
    return $a = 'error';
  }
}

所以基本上,默认情况下,$b = 将被设置为"true",我们可以修改它,$a 应该被填充。

调用示例:

getVar($a: 'input');

在这里,我们可以随时将 $b 设置为 false,而无需使参数的顺序与所需的函数相同:

getVar($b: false, $a: 'input');

如果这是在PHP中,我们应该像这样做:

getVar($a: 'input', $b: false);

现在,这是PHP代码,创建相同的函数:

public function getVar(String $a = '', String $b = '', bool $c = true) {
  if ($c) {
    return $a;
  } else {
    return $b;
  }
}

例如,我只想设置最后一部分,也就是 $c:

$this->getVar($c=false);

主要问题是函数中将 $c 读取为 $a。

英文:

I am a flutter developer and I used to use a function for example

String getVar({required String $a,bool $b = true}) {
  if($b){
    return $a;
  }
  else{
    return $a = 'error';
  }
}

So basically, $b = would be set as "true" by default we can modify it and $a should be filled

Calling Example:

getVar($a: 'input');

Here we can set $b to false anytime without making the order same as the required function

getVar($b: false, $a: 'input');

if it is in php, we should do like this

getVar($a: 'input',$b: false);

Now, here is the php code, making the same function

public function getVar(String $a = '',String $b = '',bool $c = true){
	if($c){
		return $a;
	}
	else{
		return $b;
	}
}

For example, I just want to set the last part which is $c

$this->getVar($c=false);

The main problem is $c is read as $a in the function

答案1

得分: 3

请记住,命名参数是PHP中的一个非常新的功能。直到PHP 8之前,所有参数都是按顺序传递的。在实现中可能存在一些尚未解决的微妙之处。然而,你应该能够在PHP 8中编写以下代码:

$this->getVar(b: false, a: 'test');

看看你写的代码:

$this->getVar($b=false, $a='test');

这不是你所想的。它将本地变量 $b 设置为 false,并将false作为第一个参数传递,并将本地变量 $a 设置为字符串 'test',然后将其作为第二个参数传递。=& 运算符已经有了预定义的含义,所以他们不得不引入 : 语法来实现命名参数。

英文:

Remember that named arguments are a very new feature in PHP. Until PHP 8, ALL arguments were passed sequentially. There may be subtleties in the implementation that have simply not been worked out. However, you should be able to write

$this->getVar(b: false, a: 'test');

in PHP 8. Looking at what you wrote:

$this->getVar($b=false, $a='test');

That doesn't do what you think. That sets the local variable $b to false, and passes false as the first parameter, and sets the local variable $a to the string 'test', and passes that as the second parameter. The '=' operator already has a predefined meaning, so they had to introduce the : syntax for named parameters.

huangapple
  • 本文由 发表于 2023年5月29日 08:39:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定