简体   繁体   中英

PHP 5 type hinting

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Acme\TaskBundle\Entity\Task;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    public function newAction(Request $request)
    {
        //code here
    }
}

I got this code off of the Symfony2 book. I am really confused on what the Request $request means.

I know the $request is a parameter. But I thought PHP doesn't allow declarations? What is the reason? Will only having newAction($request) work in the same way? Thanks for helping! :)

That code is absolutely normal. It works even if you drop the type hinting. If you do drop that though you aren't be able to catch a type error anymore (like if you call a method by providing an object of the wrong type).

At the moment PHP 5 supports type hinting only for objects and arrays, so you can do the same with arrays as shown below.

function blah(array $myArray) { //...

Type hinting works on the basis of Polymorphism as well, so your method/function will also accept objects that inherit from the specified type.

interface MyInterface {}

class MyClass implements MyInterface {}

function blah(MyInterface $object) {} // this works if you pass an instance of MyClass as well

http://www.php.net/manual/en/language.oop5.typehinting.php

http://en.wikipedia.org/wiki/Polymorphism_(computer_science)

EDIT : PHP7 now supports type hinting also for scalar variables: http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

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