In php, I'm wondering if the following are functionally equivalent?
class Foo {
public $bar;
...
public function setBar($bar) {
$this->bar = (array)$bar;
}
}
class Foo {
public $bar;
...
public function setBar(array $bar) {
$this->bar = $bar;
}
}
Which of the two is considered best practice? Does it make sense to do both?:
class Foo {
public $bar;
...
public function setBar(array $bar) {
$this->bar = (array)$bar;
}
}
They are NOT functionally equivalent.
Type Hinting: You are dictating what type must be passed. If the given value is of the incorrect type, then an error is generated. This does not cast or "convert" the passed value into a specific type.
Type Casting: Regardless of what value is passed, you are "converting" it into the correct type. If your function "needs" an array, then why let a boolean be passed and then cast it to an array?
Also, type hinting allows you to specify an object instance of a specific class. In the following, $bar
must be an instance of class Bar
or else an error is generated:
public function setBar(Bar $bar)
You can not type cast a variable to an object of a specific class.
Type Hinting from PHP docs:
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.
If strict_type is disabled, PHP will try to cast the value, for example:
function myFunction(int $bar) {
echo 'Received value: ' . $bar . ' ' . gettype($bar);
}
$foo = '12';
echo 'Passed value: ' . $foo . ' ' . gettype($foo);
myFunction($foo);
Will print:
Passed value: 12 string
Received value: 12 integer
In your case, you don't need to use both, it is prefered the second option because if possible PHP will try to cast, if not, an error will be triggered.
class Foo {
public $bar;
...
public function setBar(array $bar) {
$this->bar = $bar;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With