PHP Type Hinting: array supported, object NOT?

You cannot just say "object" when type casting an object... you must define WHICH object you are expecting.

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

class MyClass
{
    /**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }


    /**
     * Another test function
     *
     * First parameter must be an array
     */
    public function test_array(array $input_array) {
        print_r($input_array);
    }
}

// Another example class
class OtherClass {
    public $var = 'Hello World';
}

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)


I feel your pain, but I can't find a way of doing it either.

Despite what a number of other posters have said, it makes perfect sense to want 'Object' type hinting; they just haven't considered a scenario that requires it.

I am trying to do some work with the reflection API, and because of that I don't care what class is passed to my function. All I care is that it's an object. I don't want an int, a float, a string or an array. I want an object. Given that reflection is now part of PHP, it definitely makes sense to have object type hinting.


No, it can't be done. I wasn't missing anything.

Tags:

Php

Oop