Josh Petitt
Josh Petitt

Reputation: 9589

PHP - how to avoid use for extended classes when using type hinted constructors?

I want to avoid having to type the use statements for extended classes. It seems like it should be redundant, since the parent class knows the type for the type hinting?

For example I have a parent class

/* parent.php */
<?php
namespace App\ParentClass;

use App\User;
use App\Request;

class ParentClass {
    public function __construct(
        User $user,
        Request $request
    )
    {
        // do something
    }
}

and a child class

/* parent.php */
<?php
namespace App\ChildClass;

use App\ParentClass\ParentClass;

// HOW CAN I ELIMINATE HAVING TO TYPE THE use STATEMENTS HERE?
use App\User;
use App\Request;

class ChildClass extends ParentClass 
{
    public function __construct(
        User $user,
        Request $request
    )
    {
        // do something
    }
}

Upvotes: 1

Views: 42

Answers (2)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146630

Extended classes have no way to "know" the namespace of arbitrary parameters because:

  1. You can have classes with the same name in different namespaces (that's the idea of namespaces in the first place)

  2. Code in a namespace can use objects from other namespaces

  3. Child classes constructors can have entirely different parameters than parent constructors.

Upvotes: 2

cn0047
cn0047

Reputation: 17091

You cannot omit such use clause,
because you are using User and Request classes below in constructor, so php need to know about this classes.

Upvotes: 1

Related Questions