Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Type Hinting: array supported, object NOT?

Tags:

Am I missing something or there really is no support for generic object type hinting in PHP 5.x?

I find it really strange that hinting arrays is supported while hinting objects is not, at least not out of the box.

I'd like to have something like this:

function foo(object $o) 

Just as we have:

function foo(array $o) 

Example of possible use: methods of an objects collection class.

Workaround: using an interface "Object" implemented by all classes or extending all classes from a generic class "Object" and writing something like this:

function foo(Object $o) 

Well, that just ain't cute.

Using stdClass as the type hint doesn't work:

Catchable fatal error: Argument 1 passed to c::add() must be an instance of stdClass, instance of b given

like image 948
Marius Burz Avatar asked Oct 10 '09 11:10

Marius Burz


1 Answers

Since type hinting should make the client code adapt to your API, your solution with accepting interfaces seems just about right.

Look at it this way: yourMethod(array $input) gives yourMethod() an array to use, thereby you know exactly which native functions that applies and can be used by yourMethod().

If you specify your method like: yourSecondMethod(yourInterface $input) you'd also know which methods that can be applied to $input since you know about/can lookup which set of rules that accompanies the interface yourInterface.

In your case, accepting any object seems wrong, because you don't have any way of knowing which methods to use on the input. Example:

function foo(Object $o) {     return $o->thisMethodMayOrMayNotExist(); } 

(Not implying that syntax is valid)

like image 91
chelmertz Avatar answered Sep 27 '22 20:09

chelmertz