简体   繁体   中英

PHP type hinting in Laravel

I was wondering if there is any difference in using type hint in method parameters, such as:

function xyz (UserRepository $repo)

and doing the same stuff with annotations:

function xyz ($repo)
    /* @var UserRepository $repo */ 

Using a type hint like

function xyz (UserRepository $repo)

is an instruction that the compiler will understand and react to. This means, PHP will raise an error when you try to pass anything that is not a UserRepository .

Quoting from the PHP Manual:

Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.

Using the "annotation" is just documentation. It's just a hint for your IDE and a developer. It has no functional meaning when executing PHP. A user would be able to pass whatever he wants to the function, eg

$somethingElse = new SomethingElse;
xyz($somethingElse);

This would work, but then it will fail when trying to access methods on $somethingElse that belong to the UserRespository . With a type hint, you would fail early.

Note: I put annotation in quotes because it's not really an annotation as you know from other languages, like Java. PHP doesn't have annotations as of 7.2. Userland implementations exist though.

Prefer real type hints.

This is not a Laravel specific thing by the way. Type Hints are a native PHP feature.

除了戈登所说的,Laravel使用类型提示进行自动注射: https ://laravel.com/docs/5.5/container#automatic-injection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM