I\'ve been working on code that\'s intended to be used with objects, without really caring what the kind of object is. I wanted to type hint that the method being written ex
There is no built-in mechanism to do this without requiring all users of your interface to extend a specified class. But why would you want to do this anyway? What do all object types have in common that's enough to make them suitable input for your API?
In all probability you wouldn't gain anything even if able to type hint like this. On the other hand, type hinting a parameter to implement an interface (such as Traversable
) would be much more meaningful.
If you still want something akin to type hinting, the best you can do is substitute a runtime check with is_object
on the parameter.
The best way to enforce this would be to create a degenerate interface called Object
. A degenerate interface means it has no defined methods.
interface Object {
// leave blank
}
Then in your base classes, you can implement Object
.
class SomeBase implements Object {
// your implementation
}
You can now call your function as you wanted to
function myFunc (Object $obj);
myFunc($someBase);
If you pass any object which inherits from your Object
interface, this type hint will pass. If you pass in an array, int, string etc, the type hint will fail.
Typehint for stdClass
works since PHP 5.3+ (if I am not wrong).
Following is valid code using typehint for stdClass
construct:
Example test.php
:
class Test{
function hello(stdClass $o){
echo $o->name;
}
}
class Arg2 extends stdClass{
public $name = 'John';
function sayHello(){
echo 'Hello world!';
}
}
$Arg1 = new stdClass();
$Arg1->name = 'Peter';
$Arg2 = new Arg2();
$Arg2->sayHello();
$test = new Test();
// OK
$test->hello($Arg1);
$test->hello($Arg2);
// fails
$test->hello(1);
Prints out:
Hello world!
Peter
JohnCatchable fatal error: Argument 1 passed to Test::hello() must be an instance of stdClass, integer given, called in test.php on line 32 and defined in test.php on line 5