Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Hinting vs Type Casting in setters php

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;
    }
}
like image 956
mcmurphy Avatar asked Dec 05 '22 16:12

mcmurphy


2 Answers

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.

like image 84
AbraCadaver Avatar answered Dec 26 '22 16:12

AbraCadaver


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;
    }
}
like image 23
Marcio Mazzucato Avatar answered Dec 26 '22 15:12

Marcio Mazzucato