I'm trying to type hint for a specific parent object in PHP:
I've current got a standard base object class:
class stdObject
{
private $var;
public function setVar($var)
{
$this->var = $var;
return $this;
}
}
And I have a class object that extends this:
class valObject extends stdObject
{
}
In a PHP function, I want to be able to type hint so that the function can expect any object that has a parent of stdObject
, so sending in valObject
would work but not anyOldObject
.
Is this possible?
Type hinting is a concept that provides hints to function for the expected data type of arguments. For example, If we want to add an integer while writing the add function, we had mentioned the data type (integer in this case) of the parameter.
In May of 2010 support for scalar type hinting was added to the PHP trunk.
You can by using the parent type :
function test(stdObject $obj) {
// ...
}
If you don't want to have a pure stdObject as parameter, but only an object that inherit stdObject, you should put your stdObject class abstract or create an interface.
Is this possible?
Yes, what you've descrived is exactly what type hinting is for. Here is the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With