Some “basuritas”: PHP, list() and objects

I was just playing around with the Symfony Expression Language Component. Suddenly, I started to play with list() and some objects and this example came up. You can use list() and $this for assigning fields. I would not recommend it, but it just funny.

class BasuritasTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     * @dataProvider validUsersDataProvider
     * @param $id
     * @param $name
     */
    public function listForObjects(int $id, string $name)
    {
        $user = new User($id, $name); 
        $this->assertSame($id, $user->id());
        $this->assertSame($name, $user->name());
    }

    public function validUsersDataProvider()
    {
        return [
            [1, "Carlos"],
            [2, "Christian"],
            [3, "Keyvan"],
            [4, "Ricard"]
        ];
    }
}

class User
{
    private $id;
    private $name;

    public function __construct($id, $name)
    {
        list($this->id, $this->name) = [$id, $name];
    }

    public function id() : int 
    {
        return $this->id;
    }

    public function name() : string
    {
        return $this->name;
    }
}

The interesting thing is the line 34. The output:

PHPUnit 5.4.8 by Sebastian Bergmann and contributors.

....                                          4 / 4 (100%)

Time: 56 ms, Memory: 4.00MB

OK (4 tests, 8 assertions)

That’s it. Happy Friday.

  • Buenas.

    No lo he probado, ¿pero se podría hacer algo como?:

    list($this->id, $this->name) = func_get_args();

    La verdad es que eso haría la escritura de los constructores algo más rápido :)

    Un saludo.