php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #55268 Traits cannot be used as function/method typehints
Submitted: 2011-07-22 14:22 UTC Modified: 2011-07-22 15:53 UTC
From: php-bugs at majkl578 dot cz Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 5.4SVN-2011-07-22 (snap) OS: Irrelevant
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: php-bugs at majkl578 dot cz
New email:
PHP Version: OS:

 

 [2011-07-22 14:22 UTC] php-bugs at majkl578 dot cz
Description:
------------
It is not possible to use trait as a typehint in function declaration.

Use case: Extending few different classes to use a trait in them where these classes doesn't have same parent. Then I want to specify typehint, because I require some methods which are declared by that trait.

Test script:
---------------
trait Foo
{}

class Bar {
	use Foo;
}

function test(Foo $obj) {
	echo 'hello';
}

test(new Bar);

Expected result:
----------------
hello

Actual result:
--------------
Catchable fatal error: Argument 1 passed to test() must be an instance of Foo, instance of Bar given...

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-07-22 14:36 UTC] rasmus@php.net
-Status: Open +Status: Bogus
 [2011-07-22 14:36 UTC] rasmus@php.net
Three things I don't understand here.

1. $obj is clearly an instance of Bar, even if the type-hint worked, it wouldn't 
be of type Foo

2. An empty trait makes no sense. This is a NOP.

3. A trait is not a type in any way. It is just a code snippet.
 [2011-07-22 15:05 UTC] php-bugs at majkl578 dot cz
Maybe the example was too brief.

1. It was intended to work the same way as interfaces do: function foo(SomeInterface $foo) where $foo must be any class implementing SomeInterface or any of its subclass.

2. Obviously, it was empty just to make the code short.

3. I know it's just a code snippet, but it'd be still useful for cases mentioned above.
 [2011-07-22 15:53 UTC] rasmus@php.net
But traits and interfaces are completely different. An interface is a contract a 
class has to meet and carries no implementation, while a trait is purely 
implementation. If you want to specify that a class has to have the implementation 
that a trait provides write an interface that describes the trait.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Nov 01 01:01:28 2024 UTC