Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do type hinting for an array of specific objects in php?

Tags:

php

I want to

return array(new Foo(), new Bar());

is there a way I can do type hinting for that?

like image 437
Toskan Avatar asked Sep 26 '22 10:09

Toskan


2 Answers

The short answer is no.

The slightly longer answer is that you can create your own Value Object to use as the hint, but this means that you will need to return an object instead of an array.

class Foo {};
class Bar {};

class Baz {
    private $foo;
    private $bar;

    public function __construct(Bar $bar, Foo $foo) {
        $this->bar = $bar;
        $this->foo = $foo;
    }

    public function getFoo() : Foo {
        return $this->foo;
    }

    public function getBar() : Bar {
        return $this->bar;
    }

}

function myFn() : Baz {
    return new Baz(new Bar(), new Foo());
}

$myObj = myFn();
var_dump($myObj);

Note: this requires PHP 7+ for hinting return types.

like image 132
Alin Purcaru Avatar answered Nov 02 '22 22:11

Alin Purcaru


No, as such it is not possible in PHP. PHP5 type hinting is for function and method arguments only but not return types.

However, PHP7 adds return type declarations but, similar to argument type declarations, they can only be one of:

  • a class or interface;
  • self;
  • array (without any specifics as to its contents);
  • callable;
  • bool;
  • float;
  • int;
  • string

If you're using PHP7, you can either specify just an array or create a class that would hold those two objects and use that as return type.

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

http://php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration

like image 36
pilsetnieks Avatar answered Nov 02 '22 22:11

pilsetnieks