setter 中的类型提示与类型转换 php
Type Hinting vs Type Casting in setters php
在php中,我想知道以下是否在功能上是等价的?
class Foo {
public $bar;
...
public function setBar($bar) {
$this->bar = (array)$bar;
}
}
class Foo {
public $bar;
...
public function setBar(array $bar) {
$this->bar = $bar;
}
}
两者中哪一个被认为是最佳做法?两者都做有意义吗?:
class Foo {
public $bar;
...
public function setBar(array $bar) {
$this->bar = (array)$bar;
}
}
它们在功能上并不等同。
类型提示:您正在指定必须传递的类型。如果给定值的类型不正确,则会生成错误。这不会将传递的值或 "convert" 转换为特定类型。
类型转换:无论传递什么值,您都"converting"将其转换为正确的类型。如果您的函数 "needs" 是一个数组,那么为什么要传递一个布尔值然后将其转换为数组?
此外,类型提示允许您指定特定 class 的对象实例。在下面,$bar
必须是 class Bar
的实例,否则会产生错误:
public function setBar(Bar $bar)
您不能将变量类型转换为特定 class 的对象。
By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.
如果 strict_type 被禁用,PHP 将尝试转换值,例如:
function myFunction(int $bar) {
echo 'Received value: ' . $bar . ' ' . gettype($bar);
}
$foo = '12';
echo 'Passed value: ' . $foo . ' ' . gettype($foo);
myFunction($foo);
将打印:
Passed value: 12 string
Received value: 12 integer
在您的情况下,您不需要同时使用两者,首选第二个选项,因为如果可能 PHP 将尝试转换,否则将触发错误。
class Foo {
public $bar;
...
public function setBar(array $bar) {
$this->bar = $bar;
}
}
在php中,我想知道以下是否在功能上是等价的?
class Foo {
public $bar;
...
public function setBar($bar) {
$this->bar = (array)$bar;
}
}
class Foo {
public $bar;
...
public function setBar(array $bar) {
$this->bar = $bar;
}
}
两者中哪一个被认为是最佳做法?两者都做有意义吗?:
class Foo {
public $bar;
...
public function setBar(array $bar) {
$this->bar = (array)$bar;
}
}
它们在功能上并不等同。
类型提示:您正在指定必须传递的类型。如果给定值的类型不正确,则会生成错误。这不会将传递的值或 "convert" 转换为特定类型。
类型转换:无论传递什么值,您都"converting"将其转换为正确的类型。如果您的函数 "needs" 是一个数组,那么为什么要传递一个布尔值然后将其转换为数组?
此外,类型提示允许您指定特定 class 的对象实例。在下面,$bar
必须是 class Bar
的实例,否则会产生错误:
public function setBar(Bar $bar)
您不能将变量类型转换为特定 class 的对象。
By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.
如果 strict_type 被禁用,PHP 将尝试转换值,例如:
function myFunction(int $bar) {
echo 'Received value: ' . $bar . ' ' . gettype($bar);
}
$foo = '12';
echo 'Passed value: ' . $foo . ' ' . gettype($foo);
myFunction($foo);
将打印:
Passed value: 12 string
Received value: 12 integer
在您的情况下,您不需要同时使用两者,首选第二个选项,因为如果可能 PHP 将尝试转换,否则将触发错误。
class Foo {
public $bar;
...
public function setBar(array $bar) {
$this->bar = $bar;
}
}