Home > Enterprise >  Function accepts Laravel collection object although only string is allowed
Function accepts Laravel collection object although only string is allowed

Time:04-26

I have just encountered a problem where I can't explain why this works.

I have a function that only accepts string type parameters.

Example class

class A {

    public function __construct() {
        $data = new \Illuminate\Support\Collection(); 
        // getType($data) => object
        $this->make($data);
    }

    private function make(string $str): string {
        // getType($str) => string
        ...
    }
}

Question: Why can I pass a collection even though only string is allowed?

CodePudding user response:

According to the docs, php will try to convert it:

By default, PHP will coerce values of the wrong type into the expected scalar type declaration if possible. For example, a function that is given an int for a parameter that expects a string will get a variable of type string.

But if you re-run you code with declare(strict_types=1);, you will get TypeError message.

CodePudding user response:

An empty collection is, per definition, an empty array. It then passes your method due to PHP's Type Juggling. This means that during the comparison of variables of different types, PHP will first convert them to a common, comparable type, which in this case will convert the array to a string.

This can be avoided by type casting your variables aswell.

You can find more information on the PHP documentation https://www.php.net/manual/en/language.types.type-juggling.php

CodePudding user response:

To avoid this behaviour you can add on top in your PHP class: declare(strict_types=1);

  • Related